The travel and tourism industry has changed drastically in the last few years thanks to the internet boom which has made it possible for users to book tickets, hotels and plan holidays at the click of a button. With the increase in the number of users using the online option for all their travel-related requirements, there is an ever-increasing demand for travel-related information like ticket availability, booking status, etc. There are a number of REST APIs that provide such data. One such API in the travel arena is the Indian Railways API. In this article, we will be learning about this API and its features.
What is the Indian Railways API?
Indian Railways operates India’s national railway system. It runs more than 10,000 passenger trains daily covering more than 7000 stations across India. Billions of passengers use the Indian Railways system to travel to several destinations across India. The Indian Railways API is an unofficial REST API for the Indian Railways.
Who can use the Indian Railways API?
Since the Indian Railways API is very simple and easy to use, educational institutes/individual learners can use it to learn how REST APIs work. Moreover, the API is completely free, so such users can make as many requests as they wish without having to worry about being charged.
Secondly, travel websites/mobile applications can also utilize the Indian Railways API. Such applications can leverage the PNR status endpoint to provide booking status to their end-users.
How does the Indian Railways API work?
The Indian Railways API is a REST API and works on REST principles. It exposes REST endpoints which are nothing but HTTP URLs. An application wishing to obtain information from the API (known as a REST client), needs to specify the endpoint URL, request parameters (information required by the endpoint to process the request), and authentication headers (API key and API host). The endpoint then processes the request and returns data corresponding to the request. By default, the response is in JSON format.
How to use the Indian Railways API?
You can use the Indian Railways API via RapidAPI. RapidAPI lists all the API endpoints and their sample responses. Moreover, it also allows executing an API endpoint from the browser itself. This feature is very useful as it allows developers to view an endpoint response in real-time without having to write any code. Additionally, RapidAPI provides code snippets for executing the API endpoints in several programming languages. Thus, developers can directly copy and use these code snippets without having to write code from scratch.
To use RapidAPI to connect to the Indian Railways API, you need to follow the steps given below.
Step 1 – Signing Up
The first step is to create a RapidAPI account as described below.
a. Enter the Indian Railways RapidAPI URL (https://rapidapi.com/blaazetech/api/indian-railways/ ) in a browser. Click on the Log In/Sign Up button in the top right corner. This redirects to the following authentication page:
b. Authenticate yourself using any of the methods shown on the page. I will choose to log in with Google. Upon successful authentication, the following page is displayed:
Step 2 – Viewing endpoint responses/executing an endpoint
As explained earlier, RapidAPI provides sample responses for all the endpoints and allows executing an endpoint and viewing the response.
To view an endpoint response/execute an endpoint, you need to do the following:
a. Click on the EndPoints tab. All the available endpoints are displayed on the left:
b. Click on the endpoint whose response you would like to view. I have selected the Find Stations endpoint. Click on the Example Response tab on the right:
c. Click the endpoint that you would like to execute. I have selected the Find Stations endpoint. Click the Test Endpoint button. View the response in the Results tab on the right:
Step 3 – Obtaining a code snippet
In order to invoke a REST endpoint programmatically, a programming language-specific HTTP client library needs to be used. Not only does RapidAPI provides code snippets in multiple programming languages, but it provides code for multiple HTTP libraries in each programming language. Thus, this code can be copied and used by an application programmer as required.
For example, to obtain a code snippet in Kotlin using the OkHttp HTTP library, you need to do the following:
a. Click on Kotlin -> OkHttp in the Code Snippets tab:
b. Copy the Kotlin code shown and use it as desired:
Indian Railways API Endpoints
Let us now take a detailed look at the Indian Railways API endpoints.
PNR Status Check
PNR stands for Passenger Name Record and is a unique number issued by the Indian Railways system per booking. The PNR status check endpoint returns the booking status of a particular PNR number. It accepts a numeric parameter called pnr. This is a mandatory parameter. It corresponds to the 10-digit PNR number whose status is required. It returns the following JSON response:
Thus, the JSON object contains details about the train number, train name, boarding date, etc. It also contains information about the booking status of each passenger.
Find Stations
The Find Stations endpoint returns a list of station codes based on the name of a station. It accepts a String parameter called station. This is a mandatory parameter. It corresponds to the name of a station. It returns the following JSON response for station=Delhi):
Thus, the JSON object contains a stations array. Each element in the array includes the station name and station code.
How to use the Indian Railway API with various programming languages
As explained earlier, RapidAPI provides code snippets to invoke the API endpoints in various programming languages. Let us now take a look at some code samples.
Using the Indian Railways API with Java
In order to use the Indian Railways API with Java, click the desired API endpoint on the left. In the code snippets tab, select Java and the desired HTTP library (ensure that you have installed this library). Copy the code snippet and use it as required.
For example, RapidAPI provides the following Java code for the Find Stations endpoint using the java.net.http library:
HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://indianrailways.p.rapidapi.com/findstations.php?station=delhi")) .header("x-rapidapi-key", "<your key here>") .header("x-rapidapi-host", "<your host here>") .method("GET", HttpRequest.BodyPublishers.noBody()) .build(); HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());
Using the Indian Railways API with Python
In order to use the Indian Railways API with Python, click the desired API endpoint on the left. In the code snippets tab, select Python and the desired HTTP library. Copy the code snippet and use it as required. For example, RapidAPI provides the following Python code for the Find Stations endpoint using the http.client library:
import http.client conn = http.client.HTTPSConnection("indianrailways.p.rapidapi.com") headers = { 'x-rapidapi-key': "<your key here>", 'x-rapidapi-host': "<your host here>" } conn.request("GET", "/findstations.php?station=delhi", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
Using the Indian Railways API with PHP
In order to use the Indian Railways API with PHP, click the desired API endpoint on the left. In the code snippets tab, select PHP and the desired HTTP library. Copy the code snippet and use it as required. For example, RapidAPI provides the following PHP code for the Find Stations endpoint using the cURL library:
<?php $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://indianrailways.p.rapidapi.com/findstations.php?station=delhi", CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => [ "x-rapidapi-host: <your host here>", "x-rapidapi-key: <your key here>" ], ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; }
Using the Indian Railways API with Ruby
In order to use the Indian Railways API with Ruby, click the desired API endpoint on the left. In the code snippets tab, select Ruby and the desired HTTP library. Copy the code snippet and use it as required. For example, RapidAPI provides the following Ruby code for the Find Stations endpoint using the Unirest library:
require 'uri' require 'net/http' require 'openssl' url = URI("https://indianrailways.p.rapidapi.com/findstations.php?station=delhi") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Get.new(url) request["x-rapidapi-key"] = '<your key here>' request["x-rapidapi-host"] = '<your host here>' response = http.request(request) puts response.read_body
Using the Indian Railways API with Javascript
In order to use the Indian Railways API with Javascript, click the desired API endpoint on the left. In the code snippets tab, select Javascript and the desired HTTP library. Copy the code snippet and use it as required. For example, RapidAPI provides the following Javascript code for the Find Stations endpoint using the jQuery library:
const settings = { "async": true, "crossDomain": true, "url": "https://indianrailways.p.rapidapi.com/findstations.php?station=delhi", "method": "GET", "headers": { "x-rapidapi-key": "<your key here>", "x-rapidapi-host": "<your host here>" } }; $.ajax(settings).done(function (response) { console.log(response); });
In addition, you can also obtain code snippets in many other programming languages/HTTP libraries from RapidAPI.
What are the benefits of the Indian Railways API?
Free – The one thing that gives the Indian Railways API an edge over other similar APIs is that it is completely free. This makes the API extremely suitable for developers/organizations looking for an inexpensive Indian Railway API solution.
Ease of Use – Secondly, the Indian Railways API is very simple and easy to use. It provides only two endpoints both of which accept very few parameters that are self-explanatory. Thus, developers can easily get started with this API in no time.
Other Similar APIs
Just like the Indian Railways API, there are many other APIs available for Indian Railways on RapidAPI. Some of these are as follows:
1. Railway Trains – India API Documentation – This API searches for trains by either train number or train name.
2. Indian Railway Live Train – This API returns live train status like current station, upcoming station, delay in minutes if any, etc.
3. PNR STATUS – INDIAN RAILWAY – This API is quite similar to the Indian Railways API and returns the status of a particular PNR number.
Summary
So, to summarize, the Indian Railways API is an unofficial API for Indian Railways. In this article, we learned about this API, its target users, its endpoints, and its benefits. We also saw how to use RapidAPI to connect to the API and obtain code snippets in different programming languages.
Leave a Reply