How to use RailPNRAPI to get PNR Status?

Here I’m sharing the sample code on How to consume API provided by railpnrapi.com to query Indian Railway PNR status:

Register yourself on http://www.railpnrapi.com/ and get/generate API Key & API Secret.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace RailPnrAPI_SampleCode
{
    class Program
    {
        static void Main(string[] args)
        {
            //set your credentials
            var apiCreds = new Dictionary
            {
                {“Key”, “”},
                {“Secret”, “”}
            };

         
            var pnr = “1234567890”; //test pnr
            var requestUrlTemplate = “http://railpnrapi.com/api/check_pnr/pnr/”+pnr+”/format/json/pbapikey/” +
                                   apiCreds[“Key”] + “/pbapisign/{0}”;

            //Get All the request parameter
            var paramsSet = new Dictionary
            {
                {“pnr”, pnr},
                {“format”, “json”},
                {“pbapikey”, apiCreds[“Key”]}
            };

            //sort the keys and concat their values
            var inputString = paramsSet.OrderBy(x => x.Key).Select(x => x.Value).Aggregate((a, b) => a + b).ToLower();
         
            //var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);
            var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);

            // compute hash
            var signature = ComputeHMACSHA1(inputString, keyBytes);

            var request = WebRequest.CreateHttp(string.Format(requestUrlTemplate, signature));
            var response = request.GetResponse();
         
            // parse JSON response using Newtonsoft.Json
            dynamic json = JsonConvert.DeserializeObject(new StreamReader(response.GetResponseStream()).ReadToEnd());
         

            // process/display response

            Console.WriteLine(“Response Code: {0}”,json.response_code);
            Console.WriteLine(“PNR: {0}”, json.pnr);
            Console.WriteLine(“Train No.: {0}”, json.train_num);
            Console.WriteLine(“Train Name: {0}”, json.train_name);
            Console.WriteLine(“DOJ: {0}”, json.doj);
            Console.WriteLine(“From Station (Code/Name): {0}/{1}”, json.from_station.code, json.from_station.name);
            Console.WriteLine(“To Station (Code/Name): {0}/{1}”, json.to_station.code, json.to_station.name);
            Console.WriteLine(“Reservation Upto (Code/Name): {0}/{1}”, json.reservation_upto.code, json.reservation_upto.name);
            Console.WriteLine(“Boarding Point (Code/Name): {0}/{1}”, json.boarding_point.code, json.boarding_point.name);
         
            Console.WriteLine(“Class: {0}”, json.@class);
            Console.WriteLine(“No. of Passengers: {0}”, json.no_of_passengers);
            Console.WriteLine(“Chart Status: {0}”, json.chart_prepared);
            Console.WriteLine();
            Console.WriteLine(“Passengers: n********************************”);
            foreach (var passenger in json.passengers)
            {
                Console.WriteLine(“Passenger #:{0}, Booking Status:{1}, Current Status:{2}”, passenger.sr, passenger.passengers, passenger.current_status);
            }
            Console.WriteLine();
            Console.WriteLine(“********************************”);

            Console.ReadLine();

        }

        private static string ComputeHMACSHA1(string input, byte[] key)
        {
            var myHmacSha1 = new HMACSHA1(key);
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            var stream = new MemoryStream(byteArray);
            byte[] hashValue = myHmacSha1.ComputeHash(stream);
            return string.Join(“”, Array.ConvertAll(hashValue, b => b.ToString(“x2”)));
        }
    }
}

     Here’s the sample console output:

Sample Code Output

Sample Code in VB
————————


Imports Newtonsoft.Json
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text

Public Class PnrResponse
    Public response_code As String = Nothing
    Public pnr As String = Nothing
    Public train_num As String = Nothing
    Public train_name As String = Nothing
    Public doj As String = Nothing
    Public from_station As Station = Nothing
    Public to_station As Station = Nothing
    Public reservation_upto As Station = Nothing
    Public boarding_point As Station = Nothing
    Public [class] As String = Nothing
    Public no_of_passengers As String = Nothing
    Public chart_prepared As String = Nothing
    Public passengers As List(Of Passenger) = Nothing
    Public [error] As String = Nothing
End Class

Public Class Station
    Public code As String = Nothing
    Public name As String = Nothing
End Class

Public Class Passenger
    Public sr As String = Nothing
    Public booking_status As String = Nothing
    Public current_status As String = Nothing
End Class

Module Module1
    Sub Main(args As String())
        ‘set your credentials
        Dim apiCreds = New Dictionary(Of String, String)() From {
            {“Key”, “”}, _
            {“Secret”, “”} _
        }
        Dim pnr = “1234567890”
        ‘test pnr
        Dim requestUrlTemplate = “http://railpnrapi.com/api/check_pnr/pnr/” + pnr + “/format/json/pbapikey/” + apiCreds(“Key”) + “/pbapisign/{0}”


        ‘Get All the request parameter
        Dim paramsSet = New Dictionary(Of String, String)() From { _
            {“pnr”, pnr}, _
            {“format”, “json”}, _
            {“pbapikey”, apiCreds(“Key”)} _
        }

        ‘sort the keys and concat their values
        Dim inputString = paramsSet.OrderBy(Function(x) x.Key).[Select](Function(x) x.Value).Aggregate(Function(a, b) a + b).ToLower()

        ‘var keyBytes = Encoding.ASCII.GetBytes(apiCreds[“Secret”]);
        Dim keyBytes = Encoding.ASCII.GetBytes(apiCreds(“Secret”))

        ‘ compute hash
        Dim signature = ComputeHMACSHA1(inputString, keyBytes)

        Dim request = WebRequest.CreateHttp(String.Format(requestUrlTemplate, signature))
        Dim response = request.GetResponse()

        ‘ parse JSON response using Newtonsoft.Json
        Dim responseText = New StreamReader(response.GetResponseStream()).ReadToEnd()
        Dim json As PnrResponse = JsonConvert.DeserializeObject(Of PnrResponse)(responseText)


        ‘ process/display response

        Console.WriteLine(“Response Code: {0}”, json.response_code)
        Console.WriteLine(“PNR: {0}”, json.pnr)
        Console.WriteLine(“Train No.: {0}”, json.train_num)
        Console.WriteLine(“Train Name: {0}”, json.train_name)
        Console.WriteLine(“DOJ: {0}”, json.doj)
        Console.WriteLine(“From Station (Code/Name): {0}/{1}”, json.from_station.code, json.from_station.name)
        Console.WriteLine(“To Station (Code/Name): {0}/{1}”, json.to_station.code, json.to_station.name)
        Console.WriteLine(“Reservation Upto (Code/Name): {0}/{1}”, json.reservation_upto.code, json.reservation_upto.name)
        Console.WriteLine(“Boarding Point (Code/Name): {0}/{1}”, json.boarding_point.code, json.boarding_point.name)

        Console.WriteLine(“Class: {0}”, json.[class])
        Console.WriteLine(“No. of Passengers: {0}”, json.no_of_passengers)
        Console.WriteLine(“Chart Status: {0}”, json.chart_prepared)
        Console.WriteLine()
        Console.WriteLine(“Passengers: ” & vbLf & “********************************”)
        For Each passenger In json.passengers
            Console.WriteLine(“Passenger #:{0}, Booking Status:{1}, Current Status:{2}”, passenger.sr, passenger.booking_status, passenger.current_status)
        Next
        Console.WriteLine()
        Console.WriteLine(“********************************”)

        Console.ReadLine()
    End Sub

    Private Function ComputeHMACSHA1(input As String, key As Byte()) As String
        Dim myHmacSha1 = New HMACSHA1(key)
        Dim byteArray As Byte() = Encoding.ASCII.GetBytes(input)
        Dim stream = New MemoryStream(byteArray)
        Dim hashValue As Byte() = myHmacSha1.ComputeHash(stream)
        Return String.Join(“”, Array.ConvertAll(hashValue, Function(b) b.ToString(“x2”)))
    End Function

End Module

——————–


Download Sample Code for C# & VB Here: Sample Codes Rail PNR API


9 thoughts on “How to use RailPNRAPI to get PNR Status?”

Leave a Comment