Getting started overview
This guide provides a structured approach to initiating development with the Land Transport Authority (LTA) DataMall APIs. The process involves registering for a developer account, obtaining API credentials, and executing a foundational API request. The LTA DataMall offers a range of public transport and traffic-related APIs for Singapore, all of which are free to use. Successful completion of these steps will enable developers to access datasets such as real-time bus arrivals, traffic incidents, and carpark availability.
The LTA DataMall APIs are designed to provide access to critical urban mobility data, supporting applications for route optimization, public transport information systems, and urban planning research. The primary method for accessing these APIs is through a unique API key, which must be included in each request header for authentication. The data is typically returned in JSON format, aligning with common web API standards for data interchange.
Before proceeding, ensure you have a stable internet connection and a development environment capable of making HTTP requests. A basic understanding of HTTP methods (GET) and JSON data structures will be beneficial. For more detailed information on specific API endpoints and data schemas, refer to the LTA DataMall developer resources.
Here's a quick reference table outlining the key steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Account Registration | Create a developer account | LTA DataMall Developer Portal |
| 2. API Key Generation | Generate your unique API key | Developer Portal Dashboard (after login) |
| 3. Make First Request | Construct and send an API call using your key | Your preferred development environment (e.g., cURL, Postman, Python) |
| 4. Parse Response | Process the JSON data returned by the API | Your application logic |
Create an account and get keys
Access to the Land Transport Authority DataMall APIs requires a registered developer account and an associated API key. This key acts as your credential for authenticating API requests. The registration process is straightforward and typically involves providing basic contact information.
Account Registration Steps:
- Navigate to the LTA DataMall Developer Resources page.
- Look for a 'Register' or 'Sign Up' link, usually prominently displayed on the page.
- Complete the registration form, providing necessary details such as your name, email address, and organization (if applicable).
- Agree to the terms and conditions. The LTA DataMall operates under Singapore's Personal Data Protection Act (PDPA), so understanding data usage policies is important.
- Submit the form. You may receive an email to verify your account; follow the instructions in the email to complete the verification process.
API Key Generation:
Once your account is registered and verified, you can proceed to generate your API key:
- Log in to your newly created LTA DataMall developer account.
- Upon successful login, you should be directed to a developer dashboard or a similar portal area.
- Locate a section related to 'API Keys', 'Credentials', or 'My Applications'.
- Follow the prompts to generate a new API key. The system will typically provide a unique alphanumeric string.
- Important: Copy and securely store your API key immediately. It is often displayed only once upon generation for security reasons. If lost, you may need to generate a new one.
The API key is a critical component for all subsequent API interactions. It identifies your application and ensures that your requests are authorized. Without a valid API key, all API calls will fail with an authentication error.
Your first request
With your API key in hand, you are ready to make your first request to the LTA DataMall API. For this example, we will use the Bus Arrival API, which provides real-time information on bus services. This API is a good starting point due to its common use case and relatively simple request parameters.
API Endpoint and Authentication:
- API Endpoint:
http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2 - Authentication: Your API key must be passed in the HTTP request header as
AccountKey. - Data Format: Responses are in JSON.
Example: Getting Bus Arrival Timings for a Specific Bus Stop
To get bus arrival timings, you need a Bus Stop Code. You can find these codes through other LTA DataMall APIs or on physical bus stops in Singapore. Let's use an example Bus Stop Code: 83139 (Bus Stop at Blk 440, Tampines St 43).
Using cURL (Command Line):
Replace YOUR_API_KEY with the actual key you generated.
curl -X GET \
'http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode=83139' \
-H 'AccountKey: YOUR_API_KEY' \
-H 'accept: application/json'
Using Python (with requests library):
First, ensure you have the requests library installed: pip install requests.
import requests
import json
api_key = "YOUR_API_KEY" # Replace with your actual API key
bus_stop_code = "83139"
url = f"http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2?BusStopCode={bus_stop_code}"
headers = {
"AccountKey": api_key,
"accept": "application/json"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
data = response.json()
# Print the full JSON response for inspection
print(json.dumps(data, indent=2))
# Example of accessing specific data
if data and data.get("Services"): # Check if 'Services' key exists
print("\n--- Bus Arrival Information ---")
for service in data["Services"]:
print(f"Service No: {service['ServiceNo']}")
if service.get('NextBus'):
print(f" Next Bus Estimated Arrival: {service['NextBus']['EstimatedArrival']}")
if service.get('NextBus2'):
print(f" Next Bus 2 Estimated Arrival: {service['NextBus2']['EstimatedArrival']}")
print("-------------------------------")
else:
print("No bus services found for this stop or data format unexpected.")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
except json.JSONDecodeError:
print("Failed to decode JSON response.")
Expected Output:
A successful response will return a JSON object containing details about bus services arriving at the specified bus stop. The structure will include an array of Services, each with details like ServiceNo, NextBus, and NextBus2 (for subsequent bus arrivals). For example:
{
"odata.metadata": "http://datamall2.mytransport.sg/ltaodataservice/$metadata#BusArrivalv2/@Element",
"BusStopCode": "83139",
"Services": [
{
"ServiceNo": "293",
"Operator": "SBST",
"NextBus": {
"OriginCode": "83009",
"DestinationCode": "83009",
"EstimatedArrival": "2026-05-29T10:30:00+08:00",
"Latitude": "1.35000",
"Longitude": "103.95000",
"VisitNumber": "1",
"Load": "SEA",
"Feature": "WAB",
"Type": "SD"
},
"NextBus2": {
"OriginCode": "83009",
"DestinationCode": "83009",
"EstimatedArrival": "2026-05-29T10:35:00+08:00",
"Latitude": "1.35100",
"Longitude": "103.95100",
"VisitNumber": "1",
"Load": "SDA",
"Feature": "WAB",
"Type": "SD"
}
}
// ... other bus services
]
}
This initial request confirms that your API key is valid and that you can successfully communicate with the LTA DataMall API. The JSON response can then be parsed and integrated into your application's logic.
Common next steps
After successfully making your first API call, consider these common next steps to further your development with LTA DataMall APIs:
- Explore Other APIs: The LTA DataMall offers a variety of APIs beyond Bus Arrivals, including Traffic Incidents API, Carpark Availability API, and Taxi Availability API. Review the full list of available APIs to identify those most relevant to your project.
- Understand Rate Limits: While the LTA DataMall APIs are free, they typically have rate limits to ensure fair usage and system stability. Consult the developer documentation for specific rate limit details and best practices for handling them, such as implementing exponential backoff for retries.
- Error Handling: Implement robust error handling in your application. This includes catching HTTP status codes (e.g., 401 for unauthorized, 404 for not found, 429 for rate limit exceeded, 5xx for server errors) and parsing error messages from the API response. Good error handling improves application stability and user experience.
- Data Parsing and Transformation: Develop logic to effectively parse and transform the JSON data received from the APIs into a format suitable for your application. This might involve filtering, sorting, or combining data from multiple API calls.
- Build a User Interface: Integrate the fetched data into a user interface. For example, display bus arrival times on a map, show traffic incidents on a dashboard, or list available carparks.
- Security Best Practices: Always keep your API key secure. Do not embed it directly into client-side code or publicly accessible repositories. For server-side applications, store it in environment variables or a secure configuration management system. For client-side access, consider using a proxy server to hide your key.
- Explore Webhooks (if available): Some real-time data APIs offer webhooks for push notifications, which can be more efficient than continuous polling for certain types of updates. Check if the LTA DataMall provides webhook functionality for relevant datasets in their developer resources. For general information on webhooks, refer to Twilio's webhook security guide.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps for typical problems:
1. Invalid API Key (401 Unauthorized)
- Symptom: The API returns an HTTP 401 status code or an error message indicating unauthorized access.
- Solution:
- Verify Key: Double-check that your
AccountKeyin the request header exactly matches the API key generated from your LTA DataMall developer account. Copy-pasting can sometimes introduce extra spaces or characters. - Header Name: Ensure the header name is precisely
AccountKey(case-sensitive). - Key Activation: Confirm that your API key is active. Sometimes newly generated keys might take a few minutes to become fully active.
- Account Status: Log back into the LTA DataMall developer portal to ensure your account is active and not suspended.
- Verify Key: Double-check that your
2. Incorrect Endpoint or Parameters (400 Bad Request, 404 Not Found)
- Symptom: The API returns an HTTP 400 or 404 status code, or a generic error message about invalid parameters.
- Solution:
- Endpoint URL: Verify that the base URL for the API endpoint is correct (e.g.,
http://datamall2.mytransport.sg/ltaodataservice/BusArrivalv2). - Parameter Names: Ensure all query parameters (e.g.,
BusStopCode) are spelled correctly and match the LTA DataMall API documentation. Parameter names are often case-sensitive. - Parameter Values: Check that the values provided for parameters (e.g.,
83139forBusStopCode) are valid and in the correct format. - HTTP Method: Confirm you are using the correct HTTP method (e.g., GET for retrieving data).
- Endpoint URL: Verify that the base URL for the API endpoint is correct (e.g.,
3. Network Issues (Connection Refused, Timeout)
- Symptom: Your request fails with a network-related error, such as a connection refusal or a timeout.
- Solution:
- Internet Connection: Verify your internet connection is stable.
- Firewall/Proxy: If you are on a corporate network, a firewall or proxy server might be blocking outgoing requests. Consult your IT department or try making the request from a different network.
- API Server Status: Although rare, the LTA DataMall API servers might be experiencing temporary downtime. Check the LTA DataMall homepage for any service announcements.
4. JSON Parsing Errors
- Symptom: Your code fails when trying to parse the API response into a JSON object.
- Solution:
- Content-Type Header: Ensure your request includes the
accept: application/jsonheader to explicitly request JSON. - Raw Response Inspection: Print the raw text content of the API response before attempting to parse it. This helps identify if the server is returning non-JSON content (e.g., HTML error pages) or malformed JSON.
- JSON Validator: Use an online JSON validator to check the raw response if you suspect malformed JSON.
- Content-Type Header: Ensure your request includes the
5. Rate Limit Exceeded (429 Too Many Requests)
- Symptom: The API returns an HTTP 429 status code.
- Solution:
- Wait: You have sent too many requests in a short period. Wait for the specified duration (often indicated in a
Retry-Afterheader) before making further requests. - Implement Backoff: Implement an exponential backoff strategy in your code to automatically retry requests after increasing intervals.
- Optimize Calls: Review your application logic to minimize unnecessary API calls.
- Wait: You have sent too many requests in a short period. Wait for the specified duration (often indicated in a