# Trainline Rail Scraper - Journeys, Fares, Stations, Railcards (`rl1987/trainline-api-scraper`) Actor

Trainline Rail Scraper pulls journey departures, daily fare calendars, station matches, UK railcards, train calling points and live service status from Trainline's anonymous mobile API. Six dataset views across four input modes: journeys, fareCalendar, stations and railcards.

- **URL**: https://apify.com/rl1987/trainline-api-scraper.md
- **Developed by:** [R.L.](https://apify.com/rl1987) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.85 / 1,000 journey rows

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Trainline Rail Scraper - Journeys, Fares, Stations, Railcards

Trainline departures, daily fare calendars, station matches, railcard catalogue entries, train calling points and live service status as flat JSON rows. One `mode` selects the slice: `journeys`, `fareCalendar`, `stations` or `railcards`. The four modes write to one dataset with six row kinds (`journey`, `fare-day`, `station`, `railcard`, `calling-point`, `service-status`), so an agent can request one slice, filter on `recordType` and join rows on `timetableId`, `travelDate` or Trainline location URNs. The Actor reads Trainline's anonymous mobile API JSON directly, with no browser, login or API key. A captured London Euston to Manchester Piccadilly day for 2026-11-25 held 63 departures; standard fares were present on 63 of 63 rows and first-class fares on 54 of 63. Full I/O schemas: https://keyspace.dev/data-dictionaries/trainline/index.html

### What can I extract from Trainline?

Four modes cover the data Trainline serves without a login, and two toggles add per-train detail. Every delivered row carries `recordType`, `scrapedAt` (ISO 8601 UTC) and `provenance` (actor id, build and row kind).

| Mode or toggle | Input used | Dataset view / row kind | Main columns | Billable event |
| --- | --- | --- | --- | --- |
| `journeys` (default) | `origin`, `destination`, `departureDate`, optional `returnDate` | `journeys` / `journey` | `departAt`, `arriveAt`, `durationMinutes`, `changes`, `carriers`, `standardPrice`, `firstPrice`, `legs` | `journey-row` |
| `fareCalendar` | `origin`, `destination`, `fromDate`, `toDate` | `fareCalendar` / `fare-day` | `travelDate`, `cheapestStandardPrice`, `cheapestFirstPrice`, `fastestDurationMinutes`, `journeyCount` | `fare-day-row` |
| `stations` | `stationQueries` | `stations` / `station` | `query`, `name`, `code`, `shortName`, `locationType`, `countryCode`, `latitude`, `longitude`, `timezone`, `score` | `station-row` |
| `railcards` | no extra input; `includeRailcardTerms` adds detail | `railcards` / `railcard` | `code`, `name`, `price`, `currency`, `validityPeriod`, `vendor`, `termsSummary`, `termsUrl` | `railcard-row`, plus `railcard-terms` when terms are fetched |
| `includeCallingPoints` on | `journeys` or `fareCalendar` | `callingPoints` / `calling-point` | `timetableId`, `callingPointIndex`, `stationName`, `stationCrs`, `scheduledArrival`, `platformDeparture`, `realtimeArrivalStatus`, `realtimeDepartureStatus` | `calling-point-row` |
| `includeCallingPoints` on | `journeys` or `fareCalendar` | `serviceStatus` / `service-status` | `timetableId`, `isCancelled`, `delayReasons`, `disruptionCount`, `disruptionMessages`, `callingPointCount`, `stopsWithRealtime` | `service-status-row` |

The `maxItems` cap stops delivery across all row kinds together. Rows that are duplicates, rejected as empty, or cut by `maxItems` are not delivered and not billed.

### What does one row contain?

A `journey` row is one departure, not one route. It holds scheduled `departAt` and `arriveAt` with offsets, `duration` as the feed's `HH:MM:SS` string plus `durationMinutes` as an integer, `changes` (legs minus one), `carriers` in leg order, `standardPrice`, `firstPrice`, `currency` and the API's own tags. `legs[]` keeps each leg's origin and destination CRS codes, operator, `timetableId` and `transportMode`, so a trip that starts on the Underground is recorded as `rapidtransit` rather than flattened to train. In the captured 2026-11-25 sample, 47 of 63 departures had no change of train; the leg modes were 79 train legs, one bus leg and one rapidtransit leg.

`firstPrice` is null when the departure sells no first-class fare. In the same 63-row sample it was present on 54 rows and null on 9; the standard fare was present on all 63. `durationMinutes` is null if the feed's duration string is missing or not `HH:MM[:SS]`. A row is withheld entirely when it has no departure time or no standard fare.

A `fare-day` row collapses all departures on one travel date into `cheapestStandardPrice`, `cheapestFirstPrice`, the times of the lowest standard fare (`cheapestDepartAt`, `cheapestArriveAt`), `cheapestDurationMinutes`, `fastestDurationMinutes` and `journeyCount`. The three-day captured window for 2026-11-25 to 2026-11-27 had 63, 63 and 64 journeys on its three dates. `cheapestFirstPrice` is null when no journey that day sold a first-class fare, and `fastestDurationMinutes` can differ from `cheapestDurationMinutes`.

A `station` row repeats the `query`, the matched place's name and Trainline `urn:trainline:generic:loc:...` code, its short code, place type, country, latitude, longitude, timezone and a `score` from 0 to 1. Ranked places that do not genuinely match the query are dropped before delivery. A `railcard` row holds the catalogue code, name, price, currency, `validityPeriod` such as `P1Y` or `P3Y`, and vendor; `termsSummary` and `termsUrl` are filled only when `includeRailcardTerms` is on.

A `calling-point` row gives one stop's `stationCrs`, scheduled arrival and departure, live status and times, platforms and cancellation reason. A `service-status` row summarises that train: cancellation, delay and disruption messages, `callingPointCount` and `stopsWithRealtime`. Live-only columns are null on future dates where no real-time block exists; that is a timetable-only service, not a failed request.

### Which routes, operators, stations and railcards can I target?

`origin` and `destination` take a station or city name such as London Euston, Manchester Piccadilly, Leeds or Bristol Temple Meads, or a Trainline location URN. Names are resolved against Trainline's own place search before the journey request is made.

| Place in the captured data | Identifier or code | Role |
| --- | --- | --- |
| London Euston | `urn:trainline:generic:loc:EUS1444gb`, CRS `EUS` | Origin of the captured Euston to Manchester route |
| Manchester Piccadilly | `urn:trainline:generic:loc:MAN2968gb`, CRS `MAN` | Destination of that route |
| Northampton | `urn:trainline:generic:loc:NMP1069gb`, CRS `NMP` | Destination of service `w70601` |
| Leeds | `urn:trainline:generic:loc:LEE2731gb`, CRS `LDS` | Station-query example in the input schema |
| Roma Ostiense | ranked first for `zzzqqqxxxnonsense` | Rejected: no real match to the query |

The captured three-day window used seven operator codes: `VT` (Avanti West Coast), `AW`, `LM` (LNR & WMR), `LF`, `LT`, `EM` and `XC`. The dataset schema's `carriers` example is `VT`, and its `carrierName` example is Avanti West Coast.

The railcards mode returned 11 catalogue entries covering eight distinct codes:

| Railcard | Code | `validityPeriod` values seen |
| --- | --- | --- |
| Network Railcard | `NEW` | `P1Y` |
| Two Together Railcard | `2TR` | `P1Y` |
| Family & Friends Railcard | `FAM` | `P1Y`, `P3Y` |
| 16-25 Railcard | `YNG` | `P1Y`, `P3Y` |
| 26-30 Railcard | `TST` | `P1Y` |
| Senior Railcard | `SRN` | `P1Y`, `P3Y` |
| 16-17 Saver | `TSU` | `P1Y` |
| Annual Gold Card | `NGC` | `P1Y` |

With `includeRailcardTerms` on, the 16-25 Railcard's detail record supplies a terms summary beginning "1/3 off rail fares across Britain" and the URL `https://www.thetrainline.com/terms#railcards`. The input offers 30 currency codes including `GBP`, `EUR` and `USD`, and 16 locale codes including `en-GB`, `de-DE`, `fr-FR` and `pt-BR`. A route outside the UK priced in `GBP` is a converted price; the API returns the requested `currencyCode` with the fare.

### How do I choose dates and bound a run?

Leave `departureDate` empty and the journeys mode searches today + 7 days. In the fare calendar, an empty `fromDate` starts at today + 7 days and an empty `toDate` covers 14 days from that start; the end date can be at most 366 days after the start. The range is fetched in windows of up to 31 days, one request for each window. The run's status message names any date substituted for an empty input.

`maxItems` (default 0, meaning no limit) stops after that many rows have been delivered. `maxRequestsPerCrawl` (default 0) caps the number of requests. `maxConcurrency` defaults to 5 and accepts 1 to 50; `maxRequestRetries` defaults to 5 and `maxSessionRotations` to 10. For a day of London Euston to Manchester Piccadilly, about 63 journey rows come from only 10 to 20 distinct trains, so `includeCallingPoints` is off by default and `maxServicesPerSearch` (default 10, maximum 200) limits the extra lookups. The Actor can be started from the Console, the Apify API or a schedule with the same input fields.

### What happens when a name or timetable does not match?

Trainline's place search ranks instead of filtering. For `Euston`, one captured response carried 10 places including London Euston, Preston (Lancs) and Beeston; only London Euston survived the match check, with `score` 1.0. For `zzzqqqxxxnonsense`, the API answered 200 with 10 places led by Roma Ostiense at a score of 0.0015 at most; zero station rows were delivered. A one-character typo still resolves: `Manchestor` picked Manchester Piccadilly with a match score of 0.95. The search requires a locale, and the journey search requires a fresh conversation id; the Actor supplies both.

A route or date with no timetable answers HTTP 204 with an empty body. The Actor records a note such as "no departures found for that route and date" rather than inventing a row. The calling-points endpoint can return a DataDome challenge with HTTP 403; that is counted and noted, and journey rows from the other endpoint are unaffected. Requests that exhaust their retries are written to the `failed-requests` dataset with the URL and error, while blocked and rate-limited responses rotate the session before retrying.

### What did the captured responses contain?

The fixture responses were captured on 2026-11-20 from Trainline's anonymous mobile API. For London Euston to Manchester Piccadilly, the 2026-11-25 response held 63 journeys, the 2026-12-01 response held 67, and a three-day 2026-11-25 to 2026-11-27 window held 190 (63 + 63 + 64). Across the 63-row sample, `standardPrice` was filled on 63 of 63 rows and `firstPrice` on 54 of 63; one departure carried the feed's own tag that sets `isCheapest: true`. Those numbers describe those captured dates, not a guarantee for another route or day.

The railcard catalogue fixture held 11 entries. Service `w70601` (London Euston to Northampton, operator `LM`) produced 14 calling points, platform `8` at Euston and `stopsWithRealtime: 0` for the future travel date 2026-11-25, along with the disruption message "Northampton station will be temporarily closed overnight." A service running on the capture day, `w33951` (Avanti West Coast), had five calling points and live status on at least one stop.

### What do people ask before running this?

**Do I need a Trainline account or API key?**\
No. The Actor calls Trainline's anonymous mobile endpoints and the input schema has no credential field.

**Does it book tickets or read my bookings?**\
No. It reads departures, fares, places, railcards and service status. No booking, basket or account endpoint is called.

**What is in one journey row?**\
Scheduled departure and arrival, duration, number of changes, operator codes, both fare classes with their currency, the feed's tags and the per-leg detail including CRS codes and transport mode.

**What is in one fare-calendar row?**\
A travel date, that date's lowest standard and first-class fares, the departure and arrival of the lowest standard-fare journey, its duration, the fastest duration and the number of journeys listed for that date.

**Can I get both directions in one run?**\
Yes. Set `returnDate` in journeys mode. Each row's `direction` says `outbound` or `return`.

**Can I add live stops and delays?**\
Yes. Turn on `includeCallingPoints` in journeys or fareCalendar mode. You then get `calling-point` rows and one `service-status` row for each distinct train, capped by `maxServicesPerSearch`.

**Why did my run return no rows?**\
A date with no timetable answers HTTP 204 and the status message says so. A station name that matches nothing in the ranked response delivers zero `station` rows. Both outcomes are reported, not treated as a scrape failure.

**How do I limit what a run delivers?**\
Use `maxItems` for delivered rows, `maxRequestsPerCrawl` for requests and `maxServicesPerSearch` when calling points are on. See the Pricing tab on this Actor's page for the current charge rates.

### Where are the full input and output schemas?

The input reference (19 fields, including `mode`, `origin`, `destination`, both date pairs, `stationQueries`, `includeCallingPoints`, `includeRailcardTerms`, `currency`, `locale` and the crawl limits), all six dataset views and every field definition are documented here: https://keyspace.dev/data-dictionaries/trainline/index.html

Charge event names are listed in the mode table above; current rates are shown on the Pricing tab of this Actor's page.

# Actor input Schema

## `mode` (type: `string`):

What to scrape. journeys = every departure on one route for one travel day, each row one departure with both fare classes. fareCalendar = the cheapest fare across a range, one row per travel day. stations = station/place lookup. railcards = the UK railcard catalogue.

## `origin` (type: `string`):

Journeys and fare calendar modes. Where the trip starts: a station or city name such as "London Euston" or "Manchester Piccadilly", or a Trainline location id (urn:trainline:generic:loc:...). The name is resolved against Trainline's own station list first; a name that does not really match stops the run with an explanation instead of guessing, because the lookup ranks its answers rather than filtering them. Prefilled with a real GB route so the default run returns rows; change it for your own route.

## `destination` (type: `string`):

Journeys and fare calendar modes. Where the trip ends, in the same form as the origin. Prefilled with a real GB route so the default run returns rows; change it for your own route.

## `departureDate` (type: `string`):

Journeys mode. The travel day to list journeys for, as YYYY-MM-DD. Trainline publishes timetables roughly a year ahead; a day beyond that comes back empty rather than erroring. Leave it empty and the Actor searches today + 7 days. The input carries no fixed default date on purpose - a literal date is right on the day it is written and a past date afterwards. Every substitution is named in the run's status message.

## `returnDate` (type: `string`):

Journeys mode, optional. Set it and the return direction is scraped as well, so one run gives both legs. Leave it empty for a single direction.

## `fromDate` (type: `string`):

Fare calendar mode. First travel day of the range, as YYYY-MM-DD. The range is fetched in windows of up to 31 days, one request each. Leave it empty and the Actor searches today + 7 days. The input carries no fixed default date on purpose - a literal date is right on the day it is written and a past date afterwards. Every substitution is named in the run's status message.

## `toDate` (type: `string`):

Fare calendar mode. Last travel day of the range, inclusive, as YYYY-MM-DD. At most 366 days after the start day. Leave it empty and the Actor covers 14 days from the start day. The input carries no fixed default date on purpose. Every substitution is named in the run's status message.

## `stationQueries` (type: `array`):

Stations mode. One entry per name to look up: a station, a city or any place Trainline knows, e.g. "Leeds" or "Bristol Temple Meads". Each entry returns only the places that genuinely match it, so a misspelled name returns nothing rather than a loosely similar station.

## `includeRailcardTerms` (type: `boolean`):

Railcards mode. Also fetch each card's terms and conditions summary and description, one extra request per card. Billed as an extra railcard-terms event per enriched card; leave it off to get the catalogue only.

## `includeCallingPoints` (type: `boolean`):

Journeys and fareCalendar modes. Also fetch every stop each train calls at, with scheduled and real-time times, platforms and live running status - one request per distinct train, billed per calling-point row plus a service-status row for the train itself. Off by default: a day of London to Manchester is about 63 journeys but only 10-20 distinct trains.

## `maxServicesPerSearch` (type: `integer`):

Journeys and fareCalendar modes, when calling points are on. How many distinct trains each search may look up, so a long fare calendar cannot turn into hundreds of extra requests. 0 means no limit. The trains are taken in the order the API returns them, so the earliest departures are enriched first.

## `currency` (type: `string`):

Journeys and fare calendar modes. The currency the fares are priced in. This is the app's own enabled-currency list (30 codes, from its setup call), and the API answers a fare in it directly - GBP, EUR and USD were all confirmed to come back with that currencyCode. A route outside the UK priced in GBP is a converted price.

## `locale` (type: `string`):

Language/region for station names and place search. This is the language set Trainline's own site publishes (16), and the place search really does localise: the API requires the locale on every place search - without it the search answers HTTP 400 - so a value is always sent.

## `maxItems` (type: `integer`):

Stop after this many delivered rows and bill nothing further. 0 means no limit. Each delivered row costs one billing event (the bulk ones: a single day of London Euston to Manchester Piccadilly is about 63 journey rows, a 30-day fare calendar about 30 rows).

## `maxConcurrency` (type: `integer`):

How many requests run at once. The API answers fine at 5; raise it for a long fare calendar and lower it if you start seeing 429s.

## `maxRequestsPerCrawl` (type: `integer`):

Hard cap on the number of requests this run may make, a budget guard on top of maxItems. 0 means no cap.

## `maxRequestRetries` (type: `integer`):

How many times a failing request is retried before it is recorded in the failed-requests dataset. Blocked and rate-limited responses are retried with a new session; a validation error or a schema change is not retried at all.

## `maxSessionRotations` (type: `integer`):

How many times a session may be replaced after being blocked before the request is given up on.

## `proxyConfiguration` (type: `object`):

Apify proxy to use. The API answered 200 from this host's own egress during the reverse-engineering probes (with an intermittent DataDome challenge on the calling-points endpoint), so residential proxies are optional rather than required. Leave it empty to run without a proxy.

## Actor input object example

```json
{
  "mode": "journeys",
  "origin": "London Euston",
  "destination": "Manchester Piccadilly",
  "departureDate": "",
  "returnDate": "",
  "fromDate": "",
  "toDate": "",
  "stationQueries": [
    "Leeds",
    "Bristol Temple Meads"
  ],
  "includeRailcardTerms": false,
  "includeCallingPoints": false,
  "maxServicesPerSearch": 10,
  "currency": "GBP",
  "locale": "en-GB",
  "maxItems": 0,
  "maxConcurrency": 5,
  "maxRequestsPerCrawl": 0,
  "maxRequestRetries": 5,
  "maxSessionRotations": 10
}
```

# Actor output Schema

## `results` (type: `string`):

Every delivered row. Filter by recordType to separate journeys from fare-calendar days, stations, railcards, calling points and service status.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "origin": "London Euston",
    "destination": "Manchester Piccadilly",
    "departureDate": "",
    "returnDate": "",
    "fromDate": "",
    "toDate": ""
};

// Run the Actor and wait for it to finish
const run = await client.actor("rl1987/trainline-api-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "origin": "London Euston",
    "destination": "Manchester Piccadilly",
    "departureDate": "",
    "returnDate": "",
    "fromDate": "",
    "toDate": "",
}

# Run the Actor and wait for it to finish
run = client.actor("rl1987/trainline-api-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "origin": "London Euston",
  "destination": "Manchester Piccadilly",
  "departureDate": "",
  "returnDate": "",
  "fromDate": "",
  "toDate": ""
}' |
apify call rl1987/trainline-api-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rl1987/trainline-api-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/tj2siFWsyLemOXgmz/builds/Y8cf2rAeJ3HOspIL4/openapi.json
