Streamline Train Management with Indian Railways API Actions

26 Jun 2025
Streamline Train Management with Indian Railways API Actions

The Indian Railways Train Management API is designed to empower developers by providing seamless access to essential train-related functionalities. With a focus on real-time data, this API simplifies the process of retrieving information about train fares, schedules, and availability. By integrating these Cognitive Actions into your applications, you can enhance user experiences with fast, reliable, and accurate railway information. Whether you're building a travel app, a ticket booking system, or simply a tool for railway enthusiasts, these actions will help you deliver valuable insights with minimal effort.

Prerequisites

Before you get started, ensure you have a Cognitive Actions API key and a basic understanding of how to make API calls.

Calculate Train Fare

The Calculate Train Fare action retrieves real-time fare information for a specific train service. By providing the train number, departure station code, and destination station code, developers can access accurate fare data that customers need for planning their journeys.

  • Input Requirements:
    • trainNumber: The unique identifier for the train service (e.g., 19038).
    • departureStationCode: The code for the departure station (e.g., 'bvi').
    • destinationStationCode: The code for the destination station (e.g., 'st').
  • Expected Output: The API returns a list of fare options for various classes, along with a success message and timestamp. For example, fare information may include:
    • Class Name: "2nd Seater", Fare: 105
    • Class Name: "Sleeper", Fare: 175
    • Class Name: "1st AC", Fare: 1215
  • Use Cases for this Action: This action is particularly useful for travel applications where users need to know the cost of their journey before booking. It can also be integrated into chatbots or virtual assistants that help users plan their trips by providing fare details instantly.

```python
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "174ffc18-4b67-4487-a202-818524f469d1" # Action ID for: Calculate Train Fare

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "trainNumber": 19038,
  "departureStationCode": "bvi",
  "destinationStationCode": "st"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Search Train Information
The **Search Train Information** action allows developers to access real-time details about specific trains using a numerical query value. This action helps users find accurate information about train schedules and routes.

- **Input Requirements:** 
  - `queryValue`: A numerical identifier used in the search process (e.g., 190).

- **Expected Output:** 
  The API provides detailed information about trains that match the query, including:
  - Train Name: "Avadh Express"
  - Train Number: 19038
  - Source Station: "BARAUNI JN"
  - Destination Station: "MUMBAI BANDRA TERMINUS"

- **Use Cases for this Action:**
  This action is beneficial for applications that need to display comprehensive train information to users, such as journey planning apps or railway service websites. It can also be used in customer service solutions to help users quickly find train details.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "50471ad6-0fb0-4c8a-8afd-1a0d73c8ee81" # Action ID for: Search Train Information

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "queryValue": 190
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Retrieve Trains Between Stations
The **Retrieve Trains Between Stations** action fetches real-time train information between specified departure and destination stations. This action is crucial for users looking to plan their travel based on available train services.

- **Input Requirements:** 
  - `departureStationCode`: The code for the departure station (e.g., 'bju').
  - `destinationStationCode`: The code for the destination station (e.g., 'bdts').

- **Expected Output:** 
  The API returns a list of trains that operate between the specified stations, including:
  - Train Name: "Rxl Ltt Spl"
  - Train Number: 05545
  - Departure Time: "22:35:00"
  - Arrival Time: "05:30:00"
  
- **Use Cases for this Action:**
  This action is ideal for applications that provide travel planning tools or booking services. It can help users find the best train options based on their travel preferences, such as time of travel and available classes.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "c6722115-8b27-4288-ae5e-c9f7e5dee608" # Action ID for: Retrieve Trains Between Stations

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "departureStationCode": "bju",
  "destinationStationCode": "bdts"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Conclusion
The Indian Railways Train Management API offers a powerful suite of Cognitive Actions that enhance the travel experience by providing real-time train information, fare calculations, and scheduling details. By integrating these actions into your applications, you can deliver precise and timely information to users, thereby improving user satisfaction and engagement. Next steps could include exploring additional features of the API or developing a prototype application that utilizes these actions to streamline train management tasks.