8000 GitHub - trainiac-hq/docs: How to use the traini.ac API: live UK rail data over REST and MCP · GitHub
[go: up one dir, main page]

Skip to content
trainiac-hqPublic

About

How to use the traini.ac API: live UK rail data over REST and MCP

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

14 Commits
< 10000 h2 class="sr-only userSelectNone__I6NSfK prc-Heading-Heading-MtWFE" data-component="Heading" data-testid="screen-reader-heading" id="folders-and-files">Folders and files

Repository files navigation

Trainiac: docs for the Trainiac API and MCP server

Live UK train data, free, as typed JSON. Ask for a station's departures, plan a journey, find where a train is right now, or see today's delays and cancellations. It's all built from Network Rail's open feeds and National Rail's Darwin forecasts. Caltrain and BART in the San Francisco Bay Area are there too: add network=bay_area.

No sign-up, no API keys. Everything is a GET, and it works straight from a browser (CORS is open).

For personal, non-commercial projects only. Hobby apps, home dashboards, learning and research are all welcome; anything commercial isn't. See the terms of use.

curl 'https://api.traini.ac/v1/departures/PAD?limit=5'   # next trains from Paddington
curl 'https://api.traini.ac/v1/journey/PAD/RDG'          # Paddington to Reading
curl 'https://api.traini.ac/v1/train?headcode=1A23'      # where is 1A23?

Writing TypeScript? Every answer has a published type. Copy v1.d.ts, or generate your own from openapi.v1.json (OpenAPI 3.1).

Using it with an AI? The same data is an MCP server. In Claude Code it's one line: claude mcp add --transport http trainiac https://api.traini.ac/mcp

Coming from /api? It's legacy and will go away. MIGRATING.md maps every field to its /v1 home.

What you can ask

Base URL: https://api.traini.ac. GET /v1 lists everything as JSON.

Ask for Endpoint
The departure board at a station /v1/departures/{station}
Trains from A to B, with changes /v1/journey/{from}/{to}
Where one train is right now, or whether it's cancelled /v1/train?headcode=…
A station's code from its name /v1/stations?q=…
What actually ran at a station in the last 3 hours /v1/stations/{station}/activity
The worst delays right now /v1/delays
Today's cancellations, with reasons /v1/cancellations
Today's headline numbers /v1/summary
Whether the data is fresh right now /v1/status
Every train of a network, kept up to date on a page /v1/stream

Four things worth knowing

  1. Switch on type. Every answer, and every value that can be one of several things, says which it is in a type field. TypeScript narrows on it.
  2. Every key is always there. null means the thing doesn't exist (a train that hasn't been given an id yet), never "we don't know": not knowing is its own type, like {"type": "no_information"}.
  3. Stations can be written however you like: a code (PAD), a name (London Paddington, percent-encoded in a path) or a group (London). Answers always use proper names: London Paddington, not PADDINGTON LONDON.
  4. Times are UK time, with the offset, like 2026-10-05T14:26:00+01:00 (Bay Area time when you ask about the Bay Area). When you send a time, use HH:MM. Dates are YYYY-MM-DD. Delays are in minutes, and negative means early.

Every answer looks the same

type Answer<Request, Data> =
  | { type: "ok"; request: Request; data: Data; generated_at: string; live_data: LiveData } // HTTP 200
  | { type: "error"; error: ApiError };                                                      // HTTP 4xx/5xx

request is what we took your arguments to mean, with defaults filled in. Check it: a name becomes one specific station (or a group), and this is where you see which.

"request": {
  "station": { "query": "London", "resolution": { "type": "group", "name": "London Terminals",
    "stations": [ { "crs": "PAD", "name": "London Paddington" }, { "crs": "KGX", "name": "London Kings Cross" }, … ] } },
  "calling_at": null, "from_time": null, "to_time": null, "limit": 15, "network": "gb"
}

data can be an empty list. Empty means "no trains". A station we couldn't work out is an error, never an empty list.

live_data says whether the feeds behind the answer are arriving. When some aren't, it says which, and what that costs you in a sentence you can show.

type LiveData =
  | { type: "arriving" }                         // all of them are
  | { type: "impaired"; feeds: LiveDataFeed[] }  // these can't be relied on
  | { type: "unknown" };                         // nobody could check

type LiveDataFeed = {
  id: string;                 // "darwin", "trust", "td", "vstp", "511:CT"
  name: string;               // "National Rail forecasts"
  condition: "stopped" | "frozen" | "unmatched" | "behind" | "recovering" | "unknown";
  last_heard: string | null;  // UTC. null when nobody knows
  affects: string;            // "Expected times, platforms and delay reasons may be missing or out of date."
};

The building blocks

These appear all over. The full set, with every endpoint's request and data, is v1.d.ts.

type Station = { crs: string; name: string };

/** Somewhere a train is or calls. Junctions and sidings have no code. */
type Place =
  | { type: "station"; crs: string; name: string }
  | { type: "location"; name: string };

type Operator = { code: string; name: string | null }; // { "code": "GW", "name": "Great Western Railway" }

type ServiceClass = "passenger" | "bus" | "freight" | "ship" | "trip" | "empty_stock" | "unknown";

/** A timetabled time and what is known about it. */
type Time = {
  scheduled: string;
  estimate: Estimate;
  delay_minutes: number | null; // when the estimate has a time; negative is early
};

type Estimate =
  | { type: "actual"; at: string }                                      // it has happened
  | { type: "forecast"; at: string;                                     // expected then
      source: "darwin" | "live_report" | "trip_update" }                // trip_update: the Bay Area's
  | { type: "delayed_no_estimate" }                                     // late, nobody can say how late
  | { type: "no_information" }                                          // nothing live yet: not "on time"
  | { type: "cancelled" };                                              // won't happen

type Platform =
  | { type: "known"; number: string; source: "actual" | "forecast" | "timetable" } // "4A" is a platform
  | { type: "withheld" }                                                           // not to be shown yet
  | { type: "unknown" };

type Train = {
  id: string | null;      // TRUST id, e.g. 671L50MK02. null until the train is activated
  uid: string | null;     // timetable uid, e.g. GW001
  headcode: string;       // e.g. 1L50. These repeat across the country
  operator: Operator | null;
};

A forecast from darwin is National Rail's prediction, the best there is before a train leaves. One from live_report is how late the train was when it was last reported, carried forward. A timetable platform is planned only, and often wrong at big stations.

cancelled is about that one time. A train can run and leave out some of its stops, so read the estimate of each stop you show. To ask about the whole train, use Train.

Stations

Anywhere you give a station (in a path, or as calling_at or via) you can use:

  • a code: PAD, KGX, HDM
  • a name, in any word order: London Paddington, paddington, Haddenham & Thame Parkway (in a path: Haddenham%20%26%20Thame%20Parkway)
  • a group: London, Birmingham, Manchester, Glasgow, Edinburgh

Exact codes win, then exact names, then the busiest match, so Paddington means the main station rather than the Elizabeth line platforms. If a name really is ambiguous (bradford), you get a station_ambiguous error with candidates instead of a guess.

type StationArgument = { query: string; resolution: Resolution };
type Resolution =
  | { type: "station"; crs: string; name: string }
  | { type: "group"; name: string; stations: Station[] };

The San Francisco Bay Area

Every endpoint also answers for Caltrain and BART. Add network=bay_area to the query:

curl 'https://api.traini.ac/v1/departures/Millbrae?network=bay_area'
curl 'https://api.traini.ac/v1/journey/Palo%20Alto/Powell%20Street?network=bay_area'
curl 'https://api.traini.ac/v1/train?headcode=101&network=bay_area'
curl 'https://api.traini.ac/v1/stations?q=mission&network=bay_area'

Leave it out, or send network=gb, for Great Britain. The answers have the same shapes, with a few differences:

  • Stations have codes like CT:PLACE_MLBR (Millbrae) or BA:901509 (16th Street / Mission). Send a name or a code; /v1/stations?q= finds codes. Where Caltrain and BART share a station, it's one station.
  • Trains are found by Caltrain's train number (headcode=101) or by their train_id, like CT:101. BART's trains have no number, so their headcode is empty: use the train_id an answer gives you.
  • Times are Bay Area time, like 2026-03-02T08:21:00-08:00. Live times come from the railways' GTFS Realtime trip updates, so a forecast's source is trip_update. A time that had already passed when the train was last heard of is actual.
  • Platforms are the timetable's.
  • What the Bay Area's feeds don't say is empty: there's no coach count or formation, and a cancellation's reason is null. A cancelled train's since is when the railway last said so.
  • A train's origin and destination are the timetable's, even when it won't call there today.
  • Journeys can change between Caltrain and BART (at Millbrae) and between BART lines, up to max_changes.

If the Bay Area's feeds are down, you get a 503 with {"type": "network_unavailable"}. A network we don't know is a 400.

Bay Area data is provided by 511.org.

Endpoints

Departures

GET /v1/departures/{station}. The live departure board. 3 units.

Parameter Default Meaning
limit 15 1–100
from_time now Only trains leaving at or after this time
to_time — Only trains leaving at or before this time
calling_at — Only trains that set down here later on
network gb gb, or bay_area for the Bay Area

Late trains stay on the board until their expected time passes. A train that only sets down here isn't on it, and neither is one that only the timetable has cancelled. A train's calling points are the later stops where it sets down.

departs is cancelled when the train won't leave this station, and a calling point is cancelled when the train won't stop there. Each says so for itself. A train that leaves here can still miss its last few stops, and its destination is then where it now ends. A train that's cancelled here can start further along, so it may still make its later stops. Its origin and destination are the timetable's.

type Departure = {
  train: Train;
  service_class: ServiceClass;
  origin: Place;                         // where it starts today
  destination: Place;                    // where it ends today
  via: Place[];                          // which way round it goes, when it starts and ends here
  departs: Time;                         // from the station you asked about
  platform: Platform;
  calling_points: { station: Place; time: Time; platform: Platform }[]; // later stops, cancelled ones too
  destination_arrival: string | null;    // booked arrival at its destination
  coaches: number | null;                // from Darwin, when it says
  formation_changes: ({ type: "divides"; at: Place } | { type: "joins"; at: Place })[];
  formed_from: { headcode: string; origin: Place; expected_arrival: string | null } | null;
  delay_reason: string | null;
  advertised: boolean;                   // false: Darwin asks for this stop to be kept off boards
};
Example
curl 'https://api.traini.ac/v1/departures/Crewe?calling_at=MAN&limit=1'
{
  "type": "ok",
  "request": {
    "station": { "query": "Crewe", "resolution": { "type": "station", "crs": "CRE", "name": "Crewe" } },
    "calling_at": { "query": "MAN", "resolution": { "type": "station", "crs": "MAN", "name": "Manchester Piccadilly" } },
    "from_time": null, "to_time": null, "limit": 1, "network": "gb"
  },
  "data": [
    {
      "train": { "id": "791W60MP29", "uid": "G38988", "headcode": "1W60",
                 "operator": { "code": "AW", "name": "Transport for Wales" } },
      "service_class": "passenger",
      "origin": { "type": "station", "crs": "SWA", "name": "Swansea" },
      "destination": { "type": "station", "crs": "MAN", "name": "Manchester Piccadilly" },
      "via": [],
      "departs": {
        "scheduled": "2026-11-29T18:30:00+00:00",
        "estimate": { "type": "forecast", "at": "2026-11-29T18:44:00+00:00", "source": "darwin" },
        "delay_minutes": 14
      },
      "platform": { "type": "known", "number": "6", "source": "forecast" },
      "calling_points": [
        { "station": { "type": "station", "crs": "WML", "name": "Wilmslow" },
          "time": { "scheduled": "2026-11-29T18:48:00+00:00",
                    "estimate": { "type": "forecast", "at": "2026-11-29T19:01:00+00:00", "source": "darwin" },
                    "delay_minutes": 13 },
          "platform": { "type": "known", "number": "3", "source": "forecast" } },
        …
      ],
      "destination_arrival": "2026-11-29T19:14:00+00:00",
      "coaches": 5,
      "formation_changes": [],
      "formed_from": null,
      "delay_reason": "This train has been delayed by train crew being delayed",
      "advertised": true
    }
  ],
  "generated_at": "2026-11-29T18:32:32+00:00",
  "live_data": { "type": "arriving" }
}

Journey

GET /v1/journey/{from}/{to}. Trains between two stations over the next 24 hours, including ones with changes, in departure order. Connections are checked against live running. 5 units, or 2 with max_changes=0.

Trains that only set down at from, or only pick up at to, aren't listed. A direct train that won't leave from, or won't get to to, stays in the list with both its times cancelled, unless only the timetable has cancelled it. A journey with changes is left out when any of its trains won't make the stops it needs.

Parameter Default Meaning
via — Only journeys by way of this station, whether you change there or stay on the train
limit 10 1–100 options
max_changes 1, or 4 with via 0–8. 0 means direct trains only
min_interchange_min 5 1–60. The least time to allow for a change
from_time / to_time now / — When to leave, UK time
network gb gb, or bay_area for the Bay Area
type Journey =
  | { type: "direct"; departs: Time; arrives: Time; duration_minutes: number; leg: Leg }
  | { type: "with_changes"; departs: Time; arrives: Time; duration_minutes: number;
      legs: Leg[]; connections: Connection[] }; // connections[i] joins legs[i] to legs[i + 1]

type Leg = {
  train: Train;
  service_class: ServiceClass;
  from: Place | null;    // null only when you asked from a group and we can't say which station
  departs: Time;
  departure_platform: Platform;
  to: Place;
  arrives: Time;
  arrival_platform: Platform;
  coaches: number | null;
};

type Connection = {
  at: Place;
  minutes: number;                          // timetabled time to change
  outlook: "safe" | "at_risk" | "unknown";  // at_risk: live running eats into the change
};
Example
{
  "type": "direct",
  "departs": { "scheduled": "2026-11-29T18:30:00+00:00",
               "estimate": { "type": "forecast", "at": "2026-11-29T18:44:00+00:00", "source": "darwin" },
               "delay_minutes": 14 },
  "arrives": { "scheduled": "2026-11-29T19:14:00+00:00",
               "estimate": { "type": "forecast", "at": "2026-11-29T19:19:00+00:00", "source": "darwin" },
               "delay_minutes": 5 },
  "duration_minutes": 44,
  "leg": {
    "train": { "id": "791W60MP29", "uid": "G38988", "headcode": "1W60",
               "operator": { "code": "AW", "name": "Transport for Wales" } },
    "service_class": "passenger",
    "from": { "type": "station", "crs": "CRE", "name": "Crewe" },
    "departs": { … },
    "departure_platform": { "type": "known", "number": "6", "source": "forecast" },
    "to": { "type": "station", "crs": "MAN", "name": "Manchester Piccadilly" },
    "arrives": { … },
    "arrival_platform": { "type": "known", "number": "8", "source": "forecast" },
    "coaches": 5
  }
}

A journey with changes has legs and connections instead of leg:

"connections": [ { "at": { "type": "station", "crs": "SWI", "name": "Swindon" }, "minutes": 5, "outlook": "at_risk" } ]

Train

GET /v1/train?headcode=1A23 or GET /v1/train?train_id=171A23MN16. Where one train is right now, or when and why it was cancelled. 1 unit.

Parameter Meaning
headcode The four-character train number, e.g. 1A23
train_id The exact id from a departure, journey or cancellation. Never ambiguous
operator, origin, destination Narrow a headcode down
date The day it runs, YYYY-MM-DD. Defaults to the last 12 hours and the next 12
network gb (the default), or bay_area for the Bay Area

You need headcode or train_id. Headcodes repeat, so a headcode alone can return up to ten trains, most recently seen first. A train that hasn't been seen yet, like most cancelled ones, only comes back when no other with its headcode has been. To be sure of it, ask for its train_id. If it hasn't one yet, narrow the headcode down.

type TrainRun = {
  train: Train;
  run_date: string;
  origin: Place | null;        // where it starts and ends today
  destination: Place | null;   // null when no timetable matched (some freight)
  progress:
    | { type: "not_started"; activated: boolean; departs: string; arrives: string | null }
    | { type: "running"; last_report: Report }
    | { type: "finished"; last_report: Report }
    | { type: "unknown"; last_report: Report } // it should have been reported again, and hasn't been
    | { type: "cancelled";             // it won't make any of the stops it had left
        since: string | null;          // when the railway said so. null when only the timetable has
        reason: string | null;         // in plain English. null when the railway hasn't said why
        planned: boolean;              // the timetable cancelled it beforehand
        departs: string | null;        // its booked times. null when no timetable matched
        arrives: string | null;
        last_report: Report | null };  // null when it was never seen
};

type Report = {                     // TRUST's or Darwin's, whichever is later
  location: Place | null;
  at: string;
  event: "arrival" | "departure";   // a train passing through is reported as a departure
  delay_minutes: number | null;     // null off its route, where nobody says how late it is
  off_route: boolean;               // it was seen somewhere its timetable doesn't go
  platform: Platform;
};

A train that's cut short (part_way in Cancellations) isn't cancelled. It's running, then finished, and its destination is where it now ends. One that will start further along is not_started, and its origin and departs are from there.

Example
{
  "train": { "id": "791W60MP29", "uid": "G38988", "headcode": "1W60",
             "operator": { "code": "AW", "name": "Transport for Wales" } },
  "run_date": "2026-11-29",
  "origin": { "type": "station", "crs": "SWA", "name": "Swansea" },
  "destination": { "type": "station", "crs": "MAN", "name": "Manchester Piccadilly" },
  "progress": {
    "type": "running",
    "last_report": {
      "location": { "type": "station", "crs": "WRE", "name": "Wrenbury" },
      "at": "2026-11-29T18:31:00+00:00", "event": "departure", "delay_minutes": 18,
      "off_route": false, "platform": { "type": "unknown" }
    }
  }
}

A train that's cancelled:

{
  "train": { "id": "541S14MJ27", "uid": "G80226", "headcode": "1S14",
             "operator": { "code": "GR", "name": "LNER" } },
  "run_date": "2026-11-27",
  "origin": { "type": "station", "crs": "KGX", "name": "London Kings Cross" },
  "destination": { "type": "station", "crs": "EDB", "name": "Edinburgh Waverley" },
  "progress": {
    "type": "cancelled",
    "since": "2026-11-27T11:05:42+00:00", "reason": "Animals on the railway", "planned": false,
    "departs": "2026-11-27T11:30:00+00:00", "arrives": "2026-11-27T15:35:00+00:00",
    "last_report": null
  }
}

A train that was cut short at Eastleigh. It was booked to go on to Winchester:

{
  "train": { "id": "862B36MG27", "uid": "L80510", "headcode": "2B36",
             "operator": { "code": "SW", "name": "South Western Railway" } },
  "run_date": "2026-11-27",
  "origin": { "type": "station", "crs": "BMH", "name": "Bournemouth" },
  "destination": { "type": "station", "crs": "ESL", "name": "Eastleigh" },
  "progress": {
    "type": "finished",
    "last_report": {
      "location": { "type": "station", "crs": "ESL", "name": "Eastleigh" },
      "at": "2026-11-27T11:39:00+00:00", "event": "arrival", "delay_minutes": 33,
      "off_route": false, "platform": { "type": "known", "number": "1", "source": "forecast" }
    }
  }
}

Nothing at all (not seen in the last 12 hours, and not in the timetable for those or the next 12) is a train_not_found error.

Station search

GET /v1/stations?q=paddington. Find a station's code. Words match in any order, best match first. 1 unit.

Add network=bay_area for the Bay Area.

type StationSearch = {
  resolves_to: Resolution | null;   // the group, alias or landmark your words name, if any
  matches: StationMatch[];
  near_misses: boolean;             // true: nothing matched as written; these are the closest
};
type StationMatch =
  | { type: "station"; crs: string; name: string; tiploc: string; stanox: string | null; calls_today: number }
  | { type: "location"; kind: "depot" | "infrastructure" | "other"; name: string; crs: string | null;
      tiploc: string; stanox: string | null; calls_today: number };
Example
{
  "resolves_to": { "type": "station", "crs": "PAD", "name": "London Paddington" },
  "matches": [
    { "type": "station", "crs": "PAD", "name": "London Paddington", "tiploc": "PADTON", "stanox": "73000", "calls_today": 1804 },
    { "type": "location", "kind": "depot", "name": "Paddington New Yard", "crs": null, "tiploc": "PADTNNY", "stanox": "73104", "calls_today": 0 }
  ],
  "near_misses": false
}

stanox and tiploc are Network Rail's location codes, for joining with other open data.

Station activity

GET /v1/stations/{station}/activity?limit=15. What actually happened at a station in the last three hours, newest first. 1 unit.

Add network=bay_area for the Bay Area.

type Movement = {
  train: { id: string; headcode: string };
  location: Place;
  event: "arrival" | "departure";
  time: MovementTime;
  platform: Platform;
  off_route: boolean;             // it was seen somewhere its timetable doesn't go
};

type MovementTime = {
  scheduled: string | null;       // null for a train off its route: it wasn't due here
  estimate: { type: "actual"; at: string };
  delay_minutes: number | null;   // null then too. Negative is early
};
Example
curl 'https://api.traini.ac/v1/stations/KGX/activity'
"data": [
  …
  {
    "train": { "id": "541D81MI27", "headcode": "1D81" },
    "location": { "type": "station", "crs": "KGX", "name": "London Kings Cross" },
    "event": "departure",
    "time": {
      "scheduled": "2026-11-27T11:17:00+00:00",
      "estimate": { "type": "actual", "at": "2026-11-27T11:28:00+00:00" },
      "delay_minutes": 11
    },
    "platform": { "type": "known", "number": "5", "source": "actual" },
    "off_route": false
  },
  {
    "train": { "id": "532F23MG27", "headcode": "2F23" },
    "location": { "type": "station", "crs": "KGX", "name": "London Kings Cross" },
    "event": "arrival",
    "time": {
      "scheduled": null,
      "estimate": { "type": "actual", "at": "2026-11-27T11:25:00+00:00" },
      "delay_minutes": null
    },
    "platform": { "type": "unknown" },
    "off_route": true
  },
  …
]

2F23 was off its route: its timetable doesn't go to King's Cross.

Delays

GET /v1/delays?min_minutes=10&limit=15&passenger_only=true. The most delayed trains running right now, worst first. 1 unit. A train that was last seen off its route isn't listed, because nobody says how late it is.

Add network=bay_area for the Bay Area.

type DelayedTrain = {
  train: Train;
  service_class: ServiceClass;
  origin: Place | null;
  destination: Place | null;
  delay_minutes: number;
  off_route: boolean;
  last_seen: { location: Place | null; at: string };
};

Cancellations

GET /v1/cancellations?limit=15&passenger_only=false. Today's trains that are cancelled, in full or part way, and yesterday's that were cancelled since midnight. The newest cancellation is first, and the reason is in plain English. 1 unit.

There's one row for each train that won't get to its destination, wh 10BC8 ether it's Network Rail (TRUST or VSTP) or National Rail (Darwin) that has cancelled it, until it's reinstated. A train that only the timetable has cancelled isn't listed, but Train knows of it.

Add network=bay_area for the Bay Area.

type Cancellation = {
  train: Train;                  // its id is null until it's activated
  service_class: ServiceClass;
  origin: Place | null;          // as booked. null when we have no name for the place
  destination: Place | null;
  cancelled:
    | { type: "before_departure"; at: Place }   // makes none of its stops. It was to start here
    | { type: "part_way"; at: Place }           // ends here, short of its destination
    | { type: "not_needed"; at: Place }         // an "on call" train that wasn't called on
    | { type: "off_booked_path"; at: Place };   // cancelled while off its booked route
  reason: { code: string; description: string; category: string; planned: boolean } | null;
  reported_at: string;   // when the railway said so
  keyed_at: string;      // when it went into TRUST: hours earlier for a planned one
};

reason and keyed_at are TRUST's. For a train that TRUST hasn't cancelled, code is Darwin's number, category is Unknown and keyed_at is reported_at. reason is null when nobody says why.

reason.planned is true for planned reductions (engineering work and the like), which you may want to leave out of a "what went wrong today" view.

Example
{
  "train": { "id": "741M42MH29", "uid": "G00867", "headcode": "1M42",
             "operator": { "code": "XC", "name": "CrossCountry" } },
  "service_class": "passenger",
  "origin": { "type": "station", "crs": "RDG", "name": "Reading" },
  "destination": { "type": "station", "crs": "MAN", "name": "Manchester Piccadilly" },
  "cancelled": { "type": "part_way", "at": { "type": "station", "crs": "MAC", "name": "Macclesfield" } },
  "reason": { "code": "M7", "description": "Door and Door system faults", "category": "Fleet or mechanical", "planned": false },
  "reported_at": "2026-11-29T15:23:58+00:00",
  "keyed_at": "2026-11-29T15:49:00+00:00"
}

A train that only Darwin has cancelled, before it was activated:

{
  "train": { "id": null, "uid": "L79799", "headcode": "1P70",
             "operator": { "code": "SW", "name": "South Western Railway" } },
  "service_class": "passenger",
  "origin": { "type": "station", "crs": "PMH", "name": "Portsmouth Harbour" },
  "destination": { "type": "station", "crs": "WAT", "name": "London Waterloo" },
  "cancelled": { "type": "before_departure", "at": { "type": "station", "crs": "PMH", "name": "Portsmouth Harbour" } },
  "reason": { "code": "574", "description": "A fault on this train", "category": "Unknown", "planned": false },
  "reported_at": "2026-11-29T17:58:47+00:00",
  "keyed_at": "2026-11-29T17:58:47+00:00"
}

Summary

GET /v1/summary. Today's headline numbers, as one object. 1 unit.

Add network=bay_area for the Bay Area.

{
  "service_date": "2026-11-29",
  "scheduled": 22095,
  "started": 12580,
  "running_now": { "count": 983, "window_minutes": 30 },
  "cancelled": { "total": 453, "planned": 37 },
  "punctuality": {
    "on_time_percent": 53.0,
    "definition": "share of public calls today whose actual was at or before the timetabled time, so to the minute, not the PPM 5/10 threshold",
    "average_lateness_minutes": 4.58
  },
  "movement_reports_today": 265488
}

running_now counts trains that were reported in the last window_minutes, at a stop or passing somewhere, and haven't got to their last stop. cancelled.total counts trains that won't run at all, so not those cut short. cancelled.planned is how many of them the timetable has cancelled too. A train that only the timetable has cancelled isn't counted anywhere.

on_time_percent counts to the minute, so it looks much worse than the official figures, which allow 5 or 10 minutes.

Status

GET /v1/status. Whether the API is answering, whether each feed is arriving, and how many trains are running. Answered from a snapshot at most 15 seconds old: 1 unit, never waits for the database.

type Status = {
  health: "ok" | "degraded";   // ok only when every feed is arriving or quiet
  feeds: { trust: Feed; td: Feed; darwin: Feed; vstp: Feed };
  trains_running: { type: "counted"; count: number } | { type: "unknown" };
  measured_at: string;
};
type Feed = {
  stale_after_seconds: number;
  condition:                 // whether it can be relied on
    | "arriving"
    | "quiet"                // silent because no trains are due
    | "behind"               // what arrives was sent a while ago
    | "recovering"           // it has only just come back
    | "stopped"
    | "unknown";             // nobody can tell
  freshness:                 // how old its newest data is
    | { type: "fresh"; last_stored_seconds_ago: number }
    | { type: "stale"; last_stored_seconds_ago: number }
    | { type: "silent" }     // nothing for hours
    | { type: "unknown" };   // we couldn't check
};

Stream

GET /v1/stream?network=bay_area. Every train of a network with its times at each stop, as server-sent events: everything first, then only what changes.

Use this for a page that shows a departure board and stays open. Open one stream and keep it. Don't ask Departures every minute from each reader's browser: a few thousand readers doing that is more than the limits allow between everyone, and their requests get refused. A stream costs 1 unit to open and nothing after.

Only network=bay_area (Caltrain and BART) has a stream so far. Asking for Great Britain, or naming no network, is a 503 network_unavailable.

const stream = new EventSource("https://api.traini.ac/v1/stream?network=bay_area");
const trains = new Map();

stream.addEventListener("snapshot", (e) => {
  trains.clear();
  for (const train of JSON.parse(e.data).trains) trains.set(train.id, train);
});
stream.addEventListener("update", (e) => {
  for (const train of JSON.parse(e.data).trains) trains.set(train.id, train);
});
stream.addEventListener("remove", (e) => {
  for (const id of JSON.parse(e.data).ids) trains.delete(id);
});
Event Data When
snapshot { at, trains } First, and again whenever the stream reconnects.
update { at, trains } A train changed or is new. Each comes whole: put it in place of the one with its id.
remove { at, ids } These trains have finished.
ping {} Every 15 seconds.
error { error, message } The stream was refused, and ends.
type StreamedTrain = {
  id: string;                 // "CT:665:2026-11-23": the train on its day
  uid: string;                // "CT:665"
  date: string;               // its service day
  headcode: string;           // Caltrain's train number; "" for BART
  operator: { code: string; name: string };
  line: string;               // "Local", "Express", "Yellow line"
  origin: Station | null;
  destination: Station | null;
  cancelled: boolean;
  source: "realtime" | "timetable";  // realtime once the railway has said anything of it
  calls: {
    station: Station;
    arrives: { scheduled: string; expected: string };
    departs: { scheduled: string; expected: string };
    calls: boolean;           // false: the railway says it will run through
  }[];
};
type Station = { type: "station"; crs: string; name: string | null };

A train is sent from three hours before it leaves its first stop until two minutes after it is expected at its last. Times are ISO 8601 on the Bay Area's clock. Until the railway says anything of a train, expected is the planned time.

To draw a station's board: take the trains with a call at that station whose departs.expected is still to come, and sort by it. "Calling at" another station is a later call with that crs. Find a station's crs with Station search.

Up to 6 streams an address. The browser's EventSource reconnects by itself, and a new snapshot follows.

When something goes wrong

Errors are {"type": "error", "error": {…}}, and the HTTP status tells you whose problem it is. Switch on error.type; message is for logs.

type ApiError = { message: string } & (
  | { type: "station_not_found"; parameter: string; query: string; did_you_mean: Station[] } // 404
  | { type: "station_ambiguous"; parameter: string; query: string; candidates: Station[] }  // 400
  | { type: "same_station" }                                                                // 400
  | { type: "parameter_out_of_range"; parameter: string; value: number; min: number; max: number } // 400
  | { type: "invalid_parameter"; parameter: string; value: string;
      expected: "integer" | "boolean" | "time" | "date" | "headcode" | "network" }          // 400
  | { type: "missing_parameter"; parameters: string[] }  // 400: give at least one of these
  | { type: "train_not_found" }                          // 404
  | { type: "not_found" }                                // 404: no such endpoint
  | { type: "method_not_allowed" }                       // 405
  | { type: "rate_limited"; retry_after_seconds: number } // 429
  | { type: "database_busy"; retry_after_seconds: number } // 503
  | { type: "database_unavailable" }                     // 503
  | { type: "query_failed" }                             // 503
  | { type: "status_unavailable"; retry_after_seconds: number } // 503
  | { type: "network_unavailable"; network: string }    // 503: that railway's feeds are down
  | { type: "internal_error" }                           // 500: our bug
);

parameter is the name you used: station, from, to, via or calling_at for stations.

GET /v1/departures/bradford                  → 400
{"type":"error","error":{"type":"station_ambiguous","parameter":"station","query":"bradford",
 "candidates":[{"crs":"BDI","name":"Bradford Interchange"},{"crs":"BDQ","name":"Bradford Forster Square"}, …],
 "message":"'bradford' (station) matches more than one station. Ask again with one of the candidates' CRS codes."}}

GET /v1/departures/PAD?from_time=25:99       → 400
{"type":"error","error":{"type":"invalid_parameter","parameter":"from_time","value":"25:99","expected":"time",
 "message":"from_time must be a time, HH:MM or HHMM; got '25:99'."}}

Use it from code

import type { Answer, Estimate } from "./v1"; // v1.d.ts from this repo

const station = "PAD";
const res = await fetch(`https://api.traini.ac/v1/departures/${station}?limit=10`);
const body = (await res.json()) as Answer<"/v1/departures/{station}">;

if (body.type === "error") {
  throw new Error(body.error.message);
}

for (const departure of body.data) {
  const time = clock(departure.departs.scheduled);
  const status = describe(departure.departs.estimate);
  console.log(`${time}  ${departure.destination.name}  ${status}`);
}

/** "2026-10-05T14:05:00+01:00" → "14:05" */
function clock(iso: string): string {
  return iso.slice(11, 16);
}

/** Every kind of estimate, so TypeScript tells you if a new one appears. */
function describe(estimate: Estimate): string {
  switch (estimate.type) {
    case "actual":
      return `left ${clock(estimate.at)}`;
    case "forecast":
      return `expected ${clock(estimate.at)}`;
    case "delayed_no_estimate":
      return "delayed";
    case "cancelled":
      return "cancelled";
    case "no_information":
      return "";
  }
}

Percent-encode station names in paths (encodeURIComponent, urllib.parse.quote). Three small examples you can run are in examples/:

  • next-train.sh: curl and jq, the next train from A to B
  • departures.ts: a departure board in your terminal (Bun), typed with v1.d.ts
  • journey.py: plan a journey and warn about tight changes (Python, no dependencies)

Use it from an AI (MCP)

The same data is a Model Context Protocol server at https://api.traini.ac/mcp, so assistants like Claude can answer "when's the next train to Reading?" with live data.

  • Claude (web, desktop and mobile): Settings → Connectors → Add custom connector, and paste https://api.traini.ac/mcp.

  • Claude Code:

    claude mcp add --transport http trainiac https://api.traini.ac/mcp
  • Any other MCP client: add a remote server over Streamable HTTP at the same URL. There's no key, and only the tools for your own trips need you to sign in.

Terms of use

The Trainiac API (everything under api.traini.ac, including the MCP server) is free for personal, non-commercial projects: things you build for yourself and your friends, hobby apps you don't charge for, home dashboards, learning, research and open-source tinkering.

It is not for commercial use. Please don't:

  • use it in a product or service that is sold, subscribed to, or carries ads, or in a business's own tools;
  • resell, redistribute or mirror its answers, or build a public copy of Trainiac (or a bulk dataset) from them;
  • try to get around the limits, for example by spreading requests across many addresses.

We can change the API, rate-limit or block any client, or withdraw access at any time, and it comes with no guarantee of being right, complete or up. Don't rely on it for anything safety-critical.

Building something commercial? The data underneath comes from Network Rail (datafeeds.networkrail.co.uk) and National Rail (opendata.nationalrail.co.uk), whose own licences cover commercial use: go to them directly. Not sure whether your project counts? Ask on Discord.

Fair use

It's free, and the limits are the same for everyone. They count units of work, not requests, across /v1, /api and /mcp together:

Request Units
Journey 5
Journey with max_changes=0 (direct trains only) 2
Departures 3
Everything else 1
  • 120 units a minute per address (about 40 departure boards). Go over and you get a 429 rate_limited with Retry-After.
  • 14 units running at once across everyone, and 9 on any one endpoint. These are shared by every caller, not counted per address. If they are taken, a request waits up to two seconds, then gets a 503 database_busy with Retry-After: 1. A page with many readers, each asking from their own browser, will meet this limit long before the one above: use the stream, which doesn't count against it.

Every answer tells you where you stand, in headers a browser can read too: X-Request-Units (what this cost), RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset and RateLimit-Policy (120;w=60).

Please honour Retry-After, cache what you can (a departure board doesn't change faster than every 30 seconds or so), and send a User-Agent that says who you are.

We log each request's time, method, route, path, query, IP address, user agent, status and duration. An MCP request has no route, path or query: we log its method, its tool, the client's name and version, and the session, and never the tool's arguments. We use the logs to keep the API working and stop abuse, and count them to see how much it's used. We keep them with no time limit. The privacy policy says the rest.

Legacy: /api

The same endpoints were first served under /api, in the MCP tools' own JSON ({generated_at, resolved, results, result_count}). That is legacy: it still works, but it will be removed once its last users have moved to /v1. Don't build anything new on it. MIGRATING.md maps every old field to its /v1 home.

Its trains, like the MCP tools', say whether they're cancelled, with cancelled_at, cancel_reason and cancel_planned. For a train off its route, planned and lateness_minutes are null. is_terminated is null when nobody can say whether a train has finished.

Where the data comes from

Network Rail's open data feeds (TRUST movements, TD berth steps, VSTP, TSR, the CIF timetable and CORPUS location names) and National Rail's Darwin Push Port; station names from uk-railway-stations. Times are what those feeds said: nothing is smoothed or made up. Data © Network Rail Infrastruct 8 ure Limi 50F2 ted and Rail Delivery Group, used under their open data licences.

The Bay Area's timetables and trip updates come from 511.org's GTFS and GTFS Realtime feeds for Caltrain and BART. Data provided by 511.org, under the 511 Open Data Agreement.

About

How to use the traini.ac API: live UK rail data over REST and MCP

Resources

Stars

3 stars

Watchers

0 watching

Forks

Contributors

0