Using Open Transport Data Swiss API with JavaScript

Open Transport Data Swiss provides a comprehensive set of APIs for developers to access data about the Swiss public transportation system. These APIs are RESTful and offer different types of data, such as schedules, routes, and geolocation data. In this blog post, we will explore how to use Open Transport Data Swiss API with JavaScript.

Authentication

Before we can use the APIs, we need to obtain an API key. To get an API key, we need to register on the Open Transport Data Swiss website. Once our registration is approved, we will receive an email with instructions on how to generate an API key.

Making Requests

All requests to the Open Transport Data Swiss API must be made via HTTPS and require authentication with the API key. We can use the fetch method for making requests.

Here is an example of how to retrieve a list of train stations:

const apiKey = "your_api_key_here";
const baseUrl = "https://api.opentransportdata.swiss/v1/stations";

fetch(baseUrl, {
  headers: {
    "Authorization": "Bearer " + apiKey
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we first declare our API key and the base URL for the API endpoint we want to access. We then make a fetch request to that endpoint with the proper authorization headers. The response is converted to JSON format and logged to the console. The catch method is used to handle any errors that may occur.

Query Parameters

Some API endpoints allow us to filter data by using query parameters. Here is an example of how to retrieve the schedule for a specific train route:

const apiKey = "your_api_key_here";
const baseUrl = "https://api.opentransportdata.swiss/v1/connections";

const departureStation = "008500020"; // Zurich HB
const arrivalStation = "008503050"; // Bern

const date = new Date().toISOString().split("T")[0]; // Today's date in ISO format

fetch(`${baseUrl}?from=${departureStation}&to=${arrivalStation}&date=${date}`, {
  headers: {
    "Authorization": "Bearer " + apiKey
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In this example, we declare the departure and arrival stations using their IDs, and the current date in ISO format. We then include these values as query parameters in the API endpoint URL. This filters the data returned by the API to only the schedule for the specified train route.

Conclusion

Using Open Transport Data Swiss API with JavaScript is easy and straightforward. We just need to retrieve an API key, make requests via HTTPS with the proper authorization headers, and use query parameters to filter the data we need. With these tools, we can build powerful applications that make use of the Swiss public transportation system.

Related APIs