Feature Image

Using PHP to fetch data about trains between stations from railwayapi using curl!


API or Application Programming Interface is a structure or well defined instructions on which a single file in the server handles all the requests which requires making a connection to the database.

PHP is still the most widely used backend programming language and with PHP7 it will keep on dominating for the near future. PHP has simplified the task to a greate level for using API and now we just need to use the curl function or method.

To make requests to any API we just need to pass the parameters to curl and it will do all the hard job of making connection and retriving the data.

Here I will show you how easily we can make an web app that will fetch data from the railwayapi.com which provides an easy API to fetch all the data about trains and railway information. We have to register to get an API key which we will use to make connections to the API.

RailwayAPI.com has excelent documentation and all the details on how to get different information from their API like trains between stations, live status, PNR check and lots more. Here i will show you how we can get the details of trains between two stations.

So to get the data we just need to make a GET request at http://api.railwayapi.com/v2/between/source/from_station_code/dest/to_station_code/date/checking_date/apikey/secret_api_key/
We have to basically replace from_station_code, to_station_code, checking_date, secret_api_key with their appropriate values. This will return JSON formatted data containing all the information we want. Here is the result JSON response shown below.




Now to do this with PHP we will use curl. Below is the code we wrapped the main curl code inside a try clause and everything inside a function. This will help you in bigger projects.
Our function railway_api_call accepts one attribute which is the link in which the curl will make the GET request. And at the end result variable will hold all the JSON data from the API server.




The above code can be used as a core to make API requests in any projects. The underlying principle is same make connection to the API and GET all the response from it then do whatever you want to do with the data.