TrainsRadar

API Pública

Documentación de la API REST de TrainsRadar

Base URL https://trainsradar.com
  • La API no envía cabeceras CORS: llámala desde un servidor, no desde el navegador en otro dominio. Para mostrar el mapa en tu web, usa el embed.
  • Un parámetro no válido (país desconocido, límite fuera de rango, día no numérico) devuelve 400 con un campo error.
  • Si reutilizas los datos, las licencias de sus fuentes exigen atribución: Fuentes de datos y licencias.
  • API v1 para empresas

API v1 para empresas

Una API de solo lectura con clave, pensada para integrarla en tu servicio: trenes en marcha y salidas en directo de los países cuya licencia de datos permite el uso comercial y la redistribución.

Especificación OpenAPI 3.1

Clave y cuota

Envía tu clave en la cabecera X-API-Key en cada petición. El plan Developer es gratuito, con una cuota baja (1.000 peticiones al día) para usos que no sean masivos. Las cabeceras X-RateLimit-* dicen cuántas te quedan; la cuota se reinicia a las 00:00 UTC.

curl -H "X-API-Key: $TRAINSRADAR_KEY" "https://trainsradar.com/api/v1/trains?country=FI"

Para pedir una clave, escríbenos a info@trainsradar.com contando qué vas a hacer con ella.

Endpoints

  • GET /api/v1
  • GET /api/v1/trains
  • GET /api/v1/trains/{id}
  • GET /api/v1/stations/{id}/departures?country=XX

Licencias

Solo salen los países con licencia comercial verificada. Cada fila lleva su campo license y cada respuesta, las atribuciones que debes mostrar junto a los datos.

Países disponibles ahora

  • Los errores llegan como {error, code}; los del servidor traen además un requestId para que podamos encontrarlos.
  • Esta API sí admite CORS: puedes llamarla desde el navegador con tu clave.
GET /api/trains
Probar

Trains currently running in one country (Spain unless `country` is given) or in all of them with country=ALL. Positions refresh about every 20 s.

Query Parameters

Parameter Description
country ISO country code (ES, DE, NL, FR, GB…, case-insensitive) or ALL. Defaults to ES. An unknown code is a 400.
type Only one train type (see Train.type), e.g. cercanias, ave, regional. Default: all
bounds Only trains inside north,south,east,west (decimal degrees)

Response

Train[]
GET /api/trains/:id

One running train by id (e.g. nl-2041) plus its last 10 recorded positions. 404 once the train is no longer running.

Response

{ train: Train, history: { lat, lng, recordedAt }[] }
GET /api/stations
Probar

Stations of one country, optionally filtered by name. country is required (400 without it).

Query Parameters

Parameter Description
q Case-insensitive substring of the station name (up to 64 characters; % and _ are literal)
country ISO country code (required)
limit Max results, 1–500 (default 50); anything else is a 400

Response

Station[] (with countryCode)
GET /api/stations/:id

Station details. Pass country: station ids are only unique within a country.

Query Parameters

Parameter Description
country ISO country code (recommended)

Response

Station (with countryCode)
GET /api/stations/:id/live
Probar

Next departures with real-time delay where the operator publishes it. This is what the station board and the embed widget show.

Query Parameters

Parameter Description
country ISO country code (ES, DE, NL, FR, GB…, case-insensitive) or ALL. Defaults to ES. An unknown code is a 400.
window Minutes ahead, 15–240 (default 90)
past Minutes back, 10–60 (default 10): trains that already left
arrivals 1 to also return arrivals (origin instead of destination)

Response

{ station, country, tz, generatedAt, departures: LiveDeparture[], arrivals?: LiveDeparture[], liveTrainsInCountry, nextDeparture, nextArrival? }
GET /api/stations/:id/board

Scheduled (timetable) departures for a whole service day. country is required.

Query Parameters

Parameter Description
country ISO country code (required)
day Next occurrence of a weekday (today included): 0 = Monday … 6 = Sunday, or its name (default: today in the station's time zone)

Response

{ scheduled: ScheduledDeparture[], availableLines: string[] }
GET /api/alerts
Probar

Service alerts currently in force (refreshed by the ingester in the last 2 hours). Alert ingestion is paused, so the list is normally empty.

Response

Alert[]
GET /api/stream

Server-Sent Events, same data as /api/trains. On connect, one "positions" event with the full Train[] snapshot. Then, about every 20 s, a "delta" event { u, r }: u lists trains that are new (complete Train) or changed (only id plus the fields that changed); r lists the ids of trains that left. Apply u by merging onto the train with the same id, then drop r.

Query Parameters

Parameter Description
country ISO country code (ES, DE, NL, FR, GB…, case-insensitive) or ALL. Defaults to ES. An unknown code is a 400.

Response

text/event-stream

Data Types

Train

{
  id: string,              // "<cc>-<operator id>", e.g. "nl-2041";
                           // Spain (Renfe) has no prefix: "23526"
  tripId: string | null,
  line: string | null,
  label: string | null,    // e.g. "NS 2041"
  lat: number,
  lng: number,
  status: "IN_TRANSIT_TO" | "STOPPED_AT" | "INCOMING_AT",  // GTFS-RT
  nextStopId: string | null,
  nextStopName: string | null,
  nextStopLat: number | null,
  nextStopLng: number | null,
  delay: number | null,    // seconds, null when the operator gives none
  type: string,            // e.g. "cercanias", "ave", "alvia", "regional", "intercity"
  operator: string | null,
  speedKmh: number | null,
  updatedAt: string,       // ISO 8601, when we last wrote the position
  fixAt: string | null,    // ISO 8601, when the source took the fix (null if it does not say)
  isInterpolated: boolean, // position estimated from the timetable
  countryCode: string
}

Station

{
  id: string,              // unique only within a country
  name: string,
  lat: number,
  lng: number,
  countryCode: string,
  hasCercanias: boolean,   // only set for some Spanish stations
  hasAtendo: boolean,      // Renfe assistance service, Spain only
  nucleus: null,           // legacy, never filled
  hasLd: false             // legacy, never filled
}

LiveDeparture

{
  scheduledTime: string,          // "HH:MM", station local time
  expectedTime: string,
  minutesToExpected: number,
  line: string | null,
  destination: string | null,
  operator: string | null,
  delaySeconds: number | null,
  platform: string | null,
  state: string,                  // e.g. "scheduled"
  trainId: string | null,         // matches Train.id when it is on the map
  distanceKm: number | null
}

Alert

{
  id: string,
  routes: string[],
  stops: string[],
  description: string,
  startTime: string,
  active: boolean
}