Switch to dark mode

Finding Journeys

A booking starts with a journey search. You give an origin, a destination and a date, and the API returns the journeys that depart on that day.

What is a journey?

A journey is a complete route from one location to another. It can include several trains (segments), with changes and stopovers between them. A stopover is an overnight stay or a longer connection.

The API does the routing, so you don't have to combine trains yourself.

Every segment has the distance one passenger travels on it, and that passenger's share of its emissions in CO2e. See Distance and CO2e.

Locations

A journey search needs an origin and a destination. A location is either a city, such as Paris, or a station, such as Paris Gare de Lyon. Each location has a stable uid, which you pass as origin and destination to journeys and the other journey queries.

Syncing all locations

We recommend storing the locations in your own system instead of calling the API for every lookup. Lookups are faster, and you decide how locations are searched and shown.

The locations query returns every location that can be searched and booked, as a paginated LocationConnection. A page holds 25 locations by default, and 100 at most.

Example: Fetch a page of locations

graphql
query Locations($after: String) {
  locations(first: 100, after: $after) {
    totalCount
    pageInfo {
      hasNextPage
      endCursor
    }
    edges {
      node {
        uid
        name
        countryCode
        isMeta
        coordinates {
          type
          coordinates
        }
      }
    }
  }
}

To get all of them, read the pages one by one:

  1. Run the query without after to get the first page.
  2. While pageInfo.hasNextPage is true, run it again with after set to the previous page's pageInfo.endCursor.
  3. Save each location in your own storage, keyed on uid.
  4. When you have read every page, remove or deactivate the stored locations that weren't in the result. Locations can be withdrawn, and this is how you stop offering them.

Sync regularly

New locations are added over time, and one that is added while you are reading the pages can be missed. Run the sync on a schedule, for example daily or weekly, to keep your copy up to date.

Meta locations

Each Location has an isMeta flag. A meta location stands for a place and not for one station: Paris instead of Paris Gare de Lyon, London instead of London Paddington.

A search from or to a meta location uses whichever station is best for the route. A traveler going from Paris to Lyon departs from Paris Gare de Lyon, and one going to London departs from Paris Nord. A search from Paris finds the right station in both cases, while a search from one station can miss the better connection.

In most cases, prefer a meta location over a station:

  • Put locations with isMeta: true first in autocomplete and search results.
  • Use the meta location when it is unclear which station the user means.
  • Use a specific station only when the user asks for it.

Read the station from the journey

A journey searched from a meta location can depart from any of its stations. Read the departure and arrival stations from the journey's segments instead of assuming them.

Searching locations via API

To search locations through the API, for example for an autocomplete field, pass a filter to the locations query. Searching your own synced copy is usually more efficient.

The filter also decides the order of the results:

  • With query, locations are ordered by relevance. The text is matched against names, parts of names and aliases, and can include a country name in English ("paris france"). Case and diacritics are ignored, so "Koln" finds "Köln". Every word has to match. A blank query counts as no query.
  • With near (a GeoJSON Point, { type: "Point", coordinates: [lng, lat] }) and no query, locations are ordered by distance from that point. Together with a query, near only decides between equally good matches. In both cases, radius leaves out locations that are more than that many meters away.
  • With neither, the order is stable. This is the order to read when you sync all locations.

countryCode and isMeta narrow the list without changing its order.

Example: Search for locations

graphql
query FindLocations {
  locations(filter: { query: "paris" }, first: 10) {
    edges {
      node {
        uid
        name
        countryCode
        isMeta
        coordinates {
          type
          coordinates
        }
      }
    }
  }
}

A list ordered by relevance or distance is ranked each time a page is read, so a location added or withdrawn between two pages can shift the rest by one place. Use such a search to find a location, not to fetch all of them. A cursor only works with the filter it came from.

Searching for journeys

Use the journeys query with an origin, a destination and a departure date. It returns the journeys that depart on that day.

Prices are in EUR by default. Use the optional currency argument for another currency.

Search the whole journey

Always search from the traveler's origin to their final destination. Don't split the route into parts and search each one. The routing engine finds better connections than a manual split, with fewer API calls.

Example: London to Rome

graphql
query Journeys {
  journeys(
    origin: { uid: "Sb0ISveC" }
    destination: { uid: "p6fERure" }
    date: "2026-12-23"
  ) {
    id
    status
    itinerary {
      ... on SegmentCollection {
        segments {
          departureAt
          identifier
        }
      }
    }
  }
}

Filter by journey type

There are three types of journey. Use the optional filter to choose which ones you get:

  • SMART (default): Balances travel time and comfort. Long routes can include an overnight stopover in a city on the way. This suits most travelers.

  • BLUEPRINT: An itinerary created in the Dashboard, with planned stopovers and set departure times. See Blueprints.

  • NON_STOP: The fastest route, without planned overnight stops. This can mean long travel days or tight connections.

Adding stopovers

Use the via argument to route a journey through one or more locations. Each one can have a duration, which sets how long the traveler stays there:

  • No duration: A change of trains at the location.
  • Hours or minutes: A longer connection.
  • Days: A stopover of one or more nights before the journey continues.

Example: London to Rome, spending 2 nights in Zürich

graphql
query Journeys {
  journeys(
    origin: { uid: "Sb0ISveC" }
    destination: { uid: "p6fERure" }
    date: "2026-12-23"
    via: [{ uid: "ObB7ATsZ", duration: "P2D" }]
  ) {
    status
    itinerary {
      ... on SegmentCollection {
        segments {
          departureAt
          identifier
        }
      }
    }
  }
}

Searching for a round trip

There is no round-trip search. Search each direction on its own (one journeys call out, one back with origin and destination swapped) and let the traveler pick a journey from each.

The two directions only come together when you price them, so that operators selling genuine return fares can quote one. Keep both journey IDs and pass them to combinedJourneyOffer.

Journey status

The parts of a journey are looked up separately, so some can succeed while others fail. The journey's status field sums them up:

  • LOADING: The search is still running.
  • SUCCESS: Every part was found.
  • ERROR: At least one part failed. Others may have succeeded.

Each SegmentCollection has its own status, which shows which parts of the journey are available.

You get the same statuses when you price the journey, where they say why a part has no offers:

Status Meaning
LOADING This part is still being looked up
SUCCESS This part was found, and priced if you asked for offers
NO_TIMETABLE There is no timetable for the date
OUTSIDE_TIMETABLE The date falls outside the period the operator has published a timetable for
ONE_DAY The departure is too soon; allow at least one day from today
NO_FARES The operator has no fares for this connection
UNABLE_TO_SELL There is no availability left
PREBOOK_NOT_POSSIBLE The operator's sales restrictions don't allow this part to be booked online
TOO_MANY_PASSENGERS The party is larger than the operator sells to in one booking
RATE_LIMITED You have made too many searches in a short time; see rate limits
INDETERMINATE The status could not be worked out because an earlier part of the journey failed
UNKNOWN Something unexpected went wrong

ERROR doesn't mean your request was wrong. A part of the journey couldn't be found, for example because of a temporary outage or because there is no timetable for it on that date.

json
{
  "__typename": "SmartJourney",
  "status": "ERROR",
  "itinerary": [
    {
      "__typename": "SegmentCollection",
      "status": "SUCCESS"
    },
    {
      "__typename": "SegmentCollection",
      "status": "NO_TIMETABLE"
    }
  ]
}

Planning period

The planningPeriod field says which days a journey is available on, so you don't have to search the same route for every date. Use it for a calendar or a date picker that only offers days when travel is possible.

Example: Get available days for a journey

query Journeys {
  journeys(
    origin: { uid: "6C9s-Z7A" }
    destination: { uid: "sJbfD64u" }
    date: "2026-12-23"
  ) {
    status
    itinerary {
      ... on SegmentCollection {
        segments {
          departureAt
          identifier
        }
        planningPeriod {
          startDate
          endDate
          bitfield
        }
      }
    }
  }
}

A PlanningPeriod has a startDate, an endDate and a bitfield. The bitfield has one bit for each day from startDate to endDate, and the bit is 1 on the days the SegmentCollection is available.

The bitfield is a hexadecimal string, so each character holds 4 days. It is padded with zeros on the right to a multiple of 4 bits. A 10-day planning period is padded to 12 bits, which is 3 characters.

function parseBitfield(bitfield, startDate, endDate) {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const totalDays = Math.floor((end - start) / (1000 * 60 * 60 * 24)) + 1

  // Convert the bitfield from hexadecimal to binary
  const bits = bitfield.split('').flatMap((char) => {
    // Convert the hexadecimal character to an integer, e.g. '4' -> 4
    const int = parseInt(char, 16)

    // Convert the integer to a binary string, e.g. 4 -> '100'
    const str = int.toString(2)

    // Compensate for leading 0's dropped by toString, e.g. '100' -> '0100'
    const padded = str.padStart(4, '0')

    // Split into individual bits
    return padded.split('')
  })

  // Trim the padding
  const days = bits.slice(0, totalDays)

  return days.reduce((acc, bit, index) => {
    // Count in UTC: in local time, daylight saving shifts a day onto its neighbor
    const date = new Date(start)
    date.setUTCDate(start.getUTCDate() + index)
    const key = date.toISOString().slice(0, 10)
    acc[key] = bit === '1'
    return acc
  }, {})
}

// Example usage:
const startDate = '2023-12-10'
const endDate = '2025-12-13'
const bitfield =
  'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFF7FFDFFFFFFFFEFFFFFFFFFFFFFFFFFFE0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'

console.log(parseBitfield(bitfield, startDate, endDate))
from datetime import datetime, timedelta
from pprint import pprint

def parse_bitfield(bitfield, planning_period_start, planning_period_end):
    def days_count(start, end):
        return (end - start).days + 1

    days_count = days_count(planning_period_start, planning_period_end)

    # The amount of bits in the whole string, padding included
    bit_length = len(bitfield) * 4

    # The amount of padding added to fill the last hexadecimal character (4 bits)
    byte_padding = bit_length - days_count

    # Convert the hex string to an integer
    binary = int(bitfield, 16) >> byte_padding

    result = []
    for i in range(days_count):
        day = planning_period_start + timedelta(days=i)

        shift_with = days_count - i - 1
        shifted = 1 << shift_with
        value = binary & shifted

        result.append((day.strftime("%Y-%m-%d"), value != 0))

    return result

# Example usage
planning_period_start = datetime.strptime("2023-12-10", "%Y-%m-%d")
planning_period_end = datetime.strptime("2025-12-13", "%Y-%m-%d")
bitfield = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFF7FFDFFFFFFFFEFFFFFFFFFFFFFFFFFFE0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

pprint(parse_bitfield(bitfield, planning_period_start, planning_period_end))
import Bitwise

defmodule Bitfield do
  def parse(bitfield, planning_period_start, planning_period_end) do
    days_count = days_count(planning_period_start, planning_period_end)

    # The amount of bits in the whole string, padding included
    bit_length = String.length(bitfield) * 4

    # The amount of padding added to fill the last hexadecimal character (4 bits)
    byte_padding = bit_length - days_count

    binary =
      bitfield
      |> String.to_integer(16)
      |> bsr(byte_padding)

    Enum.reduce(0..(days_count - 1), [], fn i, acc ->
      day = Date.add(planning_period_start, i)

      shift_with = days_count - i - 1
      shifted = 1 <<< shift_with
      value = binary &&& shifted

      [{to_string(day), value != 0} | acc]
    end)
    |> Enum.reverse()
  end

  defp days_count(start_date, end_date) do
    Date.diff(end_date, start_date) + 1
  end
end

startDate = "2023-12-10"
endDate = "2025-12-13"

bitfield =
  "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFF7FFDFFFFFFFFEFFFFFFFFFFFFFFFFFFE0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

IO.inspect(
  Bitfield.parse(
    bitfield,
    Date.from_iso8601!(startDate),
    Date.from_iso8601!(endDate)
  ),
  limit: :infinity
)
<?php
function parseBitfield($bitfield, $planningPeriodStart, $planningPeriodEnd)
{
  $start = new DateTime($planningPeriodStart);
  $end = new DateTime($planningPeriodEnd);
  $totalDays = $start->diff($end)->days + 1; // Inclusive end date

  // Convert the bitfield from hexadecimal to a binary string
  $binary = '';
  foreach (str_split($bitfield) as $char) {
    // Convert hex character to integer
    $int = hexdec($char);

    // Convert to binary, pad to 4 bits
    $binary .= str_pad(decbin($int), 4, '0', STR_PAD_LEFT);
  }

  // Trim the binary string to the exact number of days
  $days = substr($binary, 0, $totalDays);

  $result = [];
  for ($i = 0; $i < $totalDays; $i++) {
    $day = clone $start;
    $day->modify('+' . $i . ' days');
    $dateKey = $day->format('Y-m-d');
    $result[$dateKey] = $days[$i] === '1';
  }

  return $result;
}

// Example usage
$planningPeriodStart = '2023-12-10';
$planningPeriodEnd = '2025-12-13';
$bitfield = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFF7FFDFFFFFFFFEFFFFFFFFFFFFFFFFFFE0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';

$result = parseBitfield($bitfield, $planningPeriodStart, $planningPeriodEnd);
print_r($result);
?>

Using the Journey List embed

If you don't want to build the interface yourself, use the Journey List embed. It shows the journeys between two locations, with streamed results and prices.

html
<aa-journey-list
  publicApiKey="your-api-key-here"
  origin="6C9s-Z7A"
  destination="sJbfD64u"
  departureDate="2026-12-23"></aa-journey-list>

To show journeys you have already fetched, use the Journey Cards embed.