Transport for Germany

Transportation

Using Deutsche Bahn API to Retrieve Train Schedule Information

With Deutsche Bahn's API, you can easily retrieve train schedule information for any given station. In this guide, we'll walk you through some examples of how to use the API with JavaScript.

Prerequisites

Before we begin, make sure you have the following:

  • A basic understanding of JavaScript
  • A valid API key from Deutsche Bahn (you can obtain one here)
  • Your preferred text editor

Retrieving Station Information

To retrieve station information, you can use the location.name endpoint. This endpoint takes a query parameter that specifies the station you're interested in.

const endpoint = "https://api.deutschebahn.com/fahrplan-plus/v1/location.name";
const apiKey = "<Your API Key>";
const stationName = "Berlin";

fetch(`${endpoint}?query=${stationName}`, {
 headers: {
   Authorization: `Bearer ${apiKey}`,
 },
})
 .then((response) => response.json())
 .then((data) => console.log(data));

This will return a list of stations that match the provided query.

Retrieving Departure and Arrival Times

You can use the departureBoard and arrivalBoard endpoints to retrieve departure and arrival times for a given station. The station parameter specifies the station you're interested in and the date parameter specifies the date you want to retrieve information for.

const endpoint = "https://api.deutschebahn.com/fahrplan-plus/v1/departureBoard";
const apiKey = "<Your API Key>";
const stationId = "8010169"; // Station ID for Berlin Hauptbahnhof
const date = "2022-01-30";
const time = "18:00";

fetch(`${endpoint}?station=${stationId}&date=${date}&time=${time}`, {
 headers: {
   Authorization: `Bearer ${apiKey}`,
 },
})
 .then((response) => response.json())
 .then((data) => console.log(data));

This will return a list of departures from the specified station at the specified time.

const endpoint = "https://api.deutschebahn.com/fahrplan-plus/v1/arrivalBoard";
const apiKey = "<Your API Key>";
const stationId = "8010169"; // Station ID for Berlin Hauptbahnhof
const date = "2022-01-30";
const time = "18:00";

fetch(`${endpoint}?station=${stationId}&date=${date}&time=${time}`, {
 headers: {
   Authorization: `Bearer ${apiKey}`,
 },
})
 .then((response) => response.json())
 .then((data) => console.log(data));

This will return a list of arrivals to the specified station at the specified time.

Conclusion

In this guide, we've shown you how to use Deutsche Bahn's API to retrieve train schedule information for a given station. We hope you found this guide useful and it helps you in your development journey. Happy coding!

Related APIs in Transportation