Trainman provides APIs for fetching various railway data, such as train schedules, PNR status, seat availability, live running status, etc. However, the Trainman API is a premium service, so you'll need to sign up for API access via their official partner program.
Once you have access, you will receive an API key, and you can use it to query their endpoints. Below is an example of how to interact with the Trainman API in Python to fetch train details.
Steps to Use the Trainman API:
Sign Up for API Access: Visit the Trainman API website to get access and API keys.
Available Endpoints: Trainman typically offers the following endpoints:
PNR Status
Seat Availability
Train Running Status
Train Schedule
Fare Enquiry
Sample Python Code to Query Trainman API:
Here’s a sample for fetching train details like train schedule:
import requests
import json
# Your Trainman API key
api_key = 'your_api_key_here'
# Trainman API endpoint for train schedule (sample train number)
train_number = '12056'
url = f'https://api.trainman.in/v1/train/{train_number}/schedule?api_key={api_key}'
# Making a GET request to the Trainman API
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the response JSON
train_data = response.json()
# Print some relevant details
train_name = train_data['train']['name']
print(f"Train Name: {train_name}")
# Print train schedule
print("Schedule:")
for station in train_data['train']['route']:
print(f"Station: {station['name']}, Arrival: {station['arrival_time']}, Departure: {station['departure_time']}")
else:
print(f"Failed to fetch data: {response.status_code}")
Example Output:
yaml
Train Name: New Delhi - Dehradun Shatabdi
Schedule:
Station: New Delhi, Arrival: 00:00, Departure: 06:45
Station: Ghaziabad, Arrival: 07:35, Departure: 07:37
Station: Dehradun, Arrival: 12:50, Departure: 00:00
comments
API Key: Replace 'your_api_key_here' with the API key you received after registering with Trainman.
Endpoint: In the example, we are querying the schedule of a specific train by its number (12056).
Response Handling: The response will be in JSON format, and we extract and print the relevant data (e.g., train name, schedule, station information).