Accessing the iRail API with JavaScript

The iRail API is a publicly accessible API that provides real-time data on train schedules and stations in Belgium. Developers can use this API to access data and integrate it into their own applications.

To get started, you will need to register for an API key on the iRail website. Once you have your key, you can start making requests to the API endpoint.

Here are some basic JavaScript examples for accessing the iRail API:

Get all stations

To retrieve a list of all stations in Belgium, you can make a GET request to the following API endpoint:

https://hello.irail.be/api/stations/?format=json

Here's an example of how you can do this in JavaScript:

fetch("https://hello.irail.be/api/stations/?format=json&lang=en")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  });

This sends a request to the API endpoint and returns the response as JSON data.

Get train schedules

To retrieve information about train schedules, you can make a GET request to the following API endpoint:

https://hello.irail.be/api/liveboard/?id=<station_id>&format=json

Here's an example of how you can do this in JavaScript:

fetch("https://hello.irail.be/api/liveboard/?id=BE.NMBS.008814001&format=json&lang=en")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  });

This sends a request to the API endpoint with the station ID and returns the response as JSON data.

Get train details

To retrieve detailed information about a specific train, you can make a GET request to the following API endpoint:

https://hello.irail.be/api/train/?id=<train_id>&format=json

Here's an example of how you can do this in JavaScript:

fetch("https://hello.irail.be/api/train/?id=BE.NMBS.IC508&format=json&lang=en")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  });

This sends a request to the API endpoint with the train ID and returns the response as JSON data.

Conclusion

In this blog post, we have explored the basics of how to access the iRail API using JavaScript. We looked at examples for getting a list of all stations, retrieving train schedules, and getting detailed train information.

These examples are just scratching the surface of what you can do with this powerful API. With a little creativity, you can use the iRail API to build a wide variety of applications that leverage real-time train data.

Related APIs

Public APIs — A directory of free and public apis

Built by @mddanishyusuf