SDKs overview

Transport for Spain offers Software Development Kits (SDKs) and client libraries designed to facilitate integration with its various APIs, including the Real-time GTFS API, Historical Transit Data API, and Route Planning API. These SDKs abstract the underlying HTTP requests and JSON parsing, allowing developers to interact with the service using idiomatic code in their preferred programming language. The primary goals of these libraries are to streamline authentication processes, simplify data querying, and handle response parsing, reducing the boilerplate code required for application development.

The SDKs are maintained to reflect the capabilities of the Transport for Spain API, ensuring compatibility with the latest features and data formats. Developers can access the full API reference for detailed endpoint specifications and data models at the Transport for Spain API reference documentation. Consistent use of SDKs can lead to faster development cycles and fewer integration errors, particularly when working with complex API structures or requiring frequent updates from a service.

The concept of an SDK as a set of tools enabling the creation of applications for a specific platform or service is a common pattern in API development, as described in various technical guides on Mozilla's developer documentation about SDK definitions.

Official SDKs by language

Transport for Spain provides official SDKs for Python, JavaScript, and Ruby. These libraries are developed and maintained by Transport for Spain to ensure optimal performance and compatibility with their API endpoints.

Language Package Name Installation Command Maturity
Python transport-spain-sdk pip install transport-spain-sdk Stable
JavaScript @transport-spain/sdk npm install @transport-spain/sdk Stable
Ruby transport-spain-sdk gem install transport-spain-sdk Stable

Each SDK is designed to encapsulate the API's authentication mechanisms, including API key management, and provides methods that map directly to API resources. For example, methods to query real-time bus locations or retrieve historical route data are exposed through intuitive function calls within each language's SDK. Detailed instructions and comprehensive API guides are available in the Transport for Spain developer documentation.

Installation

Installing the Transport for Spain SDKs typically involves using the standard package managers for each respective language. Prior to installation, ensure that you have the correct language runtime and package manager installed on your system.

Python

To install the Python SDK, use pip, the Python package installer:

pip install transport-spain-sdk

This command fetches the latest stable version of the transport-spain-sdk from the Python Package Index (PyPI) and installs it along with any required dependencies. Verify the installation by importing the library in a Python interpreter.

JavaScript

For JavaScript environments (Node.js or browser-based applications with bundlers), use npm or yarn to install the SDK:

npm install @transport-spain/sdk
# or
yarn add @transport-spain/sdk

This command adds the @transport-spain/sdk package to your project's node_modules directory and updates your package.json file. The JavaScript SDK supports modern module systems, allowing for easy integration into web and server-side applications.

Ruby

The Ruby SDK is available as a gem. Install it using the gem command:

gem install transport-spain-sdk

This command downloads and installs the transport-spain-sdk gem, making it available for use in your Ruby projects. Ensure your Ruby environment is configured correctly to manage gems.

After installation, applications will need an API key, which can be obtained through a Transport for Spain account. The API key is then used to initialize the SDK client.

Quickstart example

This section provides basic quickstart examples for retrieving real-time vehicle positions using the Transport for Spain SDKs in Python and JavaScript.

Python Quickstart

The following Python snippet demonstrates how to initialize the SDK with an API key and fetch real-time GTFS data for a specific region. Replace "YOUR_API_KEY" with your actual Transport for Spain API key.

from transport_spain_sdk import TransportSpainClient

def get_realtime_data():
    api_key = "YOUR_API_KEY"
    client = TransportSpainClient(api_key=api_key)

    try:
        # Fetch real-time vehicle positions for a specific agency or region
        # Refer to API documentation for available parameters
        vehicle_positions = client.get_realtime_vehicle_positions(region_code="MAD")
        for position in vehicle_positions:
            print(f"Vehicle ID: {position.vehicle_id}, Latitude: {position.latitude}, Longitude: {position.longitude}")
    except Exception as e:
        print(f"Error fetching data: {e}")

if __name__ == "__main__":
    get_realtime_data()

This example initializes a client, calls a method to get vehicle positions, and iterates through the results. Further details on method parameters and return types are available in the Transport for Spain API reference.

JavaScript Quickstart (Node.js)

This JavaScript example, suitable for a Node.js environment, shows how to use the @transport-spain/sdk to retrieve real-time data. Again, replace "YOUR_API_KEY" with your valid API key.

const { TransportSpainClient } = require('@transport-spain/sdk');

async function getRealtimeData() {
  const apiKey = "YOUR_API_KEY";
  const client = new TransportSpainClient(apiKey);

  try {
    // Fetch real-time vehicle positions
    const vehiclePositions = await client.getRealtimeVehiclePositions({
      regionCode: "BCN"
    });
    vehiclePositions.forEach(position => {
      console.log(`Vehicle ID: ${position.vehicleId}, Latitude: ${position.latitude}, Longitude: ${position.longitude}`);
    });
  } catch (error) {
    console.error(`Error fetching data: ${error.message}`);
  }
}

getRealtimeData();

This asynchronous JavaScript function demonstrates client instantiation, a call to retrieve real-time data, and logging of specific data points. The SDK handles error responses and provides structured data objects. For more advanced usage, including error handling and specific filtering options, consult the official Transport for Spain documentation.

Community libraries

In addition to the official SDKs, the developer community sometimes contributes unofficial libraries or wrappers that extend functionality or provide support for other languages and frameworks. These community-driven projects can offer alternative integration approaches or specialized tools not covered by the official offerings.

As of late 2024, the official Transport for Spain documentation primarily highlights its first-party SDKs for Python, JavaScript, and Ruby. While community contributions can be valuable, developers should exercise due diligence when using unofficial libraries. Factors to consider include:

  • Maintenance Status: Is the library actively maintained and updated to reflect API changes?
  • Security: Does the library handle API keys and sensitive data securely?
  • Documentation: Is there sufficient documentation to understand and use the library effectively?
  • Community Support: Is there an active community to assist with issues or questions?

For the most reliable and up-to-date integration, Transport for Spain recommends using its official SDKs and documentation. Developers interested in contributing to community projects or exploring existing ones are encouraged to search public code repositories like GitHub or relevant developer forums. Information on contributing to open-source software, generally, is available through broader developer resources, such as those provided by AWS on open-source contributions.