Discover/Bahn API
live

Bahn APIbahn.com

Access Deutsche Bahn station search, train connections, real-time schedules, ticket offers, and regional transit associations via the bahn.com API.

Endpoint health
verified 8h ago
get_metadata
get_transit_associations
search_connections
get_station_autocomplete
3/4 passing latest checkself-healing
Endpoints
5
Updated
21d ago

What is the Bahn API?

The bahn.com API exposes 5 endpoints covering Deutsche Bahn station lookup, train connection search, ticket offers, regional transit associations, and booking metadata. Starting with get_station_autocomplete, you can resolve any German station name to a full HAFAS ID, then pass that ID directly into search_connections to retrieve scheduled departures, real-time arrival times, transfer counts, occupancy data, and indicative pricing.

Try it
Station name search query (e.g., 'Berlin', 'München Hbf')
api.parse.bot/scraper/7dfccc04-525c-426d-8322-a10e7d62cd3b/<endpoint>
Ready to send
Fill in the parameters and hit sign in to send to see live response data here.
Call it over HTTPgrab a free API key at signup
curl -X GET 'https://api.parse.bot/scraper/7dfccc04-525c-426d-8322-a10e7d62cd3b/get_station_autocomplete?query=Berlin' \
  -H 'X-API-Key: $PARSE_API_KEY'
Python SDK · recommended

Typed, relational, agent-ready

A generated client with real types, enums, and the links between objects — the structure a flat JSON response can't carry. Autocompletes in your editor and reads cleanly to coding agents.

  • Fully typed · autocompletes
  • Objects link to objects
  • Typed errors & pagination

Typed Python client. Set up the SDK in your uv project, then pull this API’s typed client:

uv add parse-sdk
uv run parse init
uv run parse add --marketplace bahn-com-api

uv run parse add --marketplace pulls a pinned snapshot of this canonical API — it won’t change underneath you. To customize it, subscribe and swap to your own copy.

"""Walkthrough: Deutsche Bahn SDK — search stations, explore metadata and transit associations."""
from parse_apis.deutsche_bahn_api import DeutscheBahn, StationNotFound

client = DeutscheBahn()

# Search for stations matching "Berlin"
for station in client.stations.search(query="Berlin", limit=5):
    print(station.name, station.lat, station.lon, station.products)

# Drill into one station to see its details
station = client.stations.search(query="München Hbf", limit=1).first()
if station:
    print(station.name, station.ext_id, station.type)

# List transit associations
for assoc in client.transitassociations.list(limit=5):
    print(assoc.description, assoc.abbreviation, assoc.has_shop)

# Get metadata about traveler types and discounts
meta = client.metadatas.get()
for tt in meta.traveler_types:
    print(tt.key, tt.is_discountable)
for dt in meta.discount_types:
    print(dt.key, dt.description, dt.classes)

# Typed error handling: catch StationNotFound
try:
    result = client.stations.search(query="Xyznonexistent99", limit=1).first()
    print("Search returned:", result)
except StationNotFound as exc:
    print(f"Station not found: {exc}")

print("exercised: stations.search / transitassociations.list / metadatas.get")
All endpoints · 5 totalmissing one? ·

Search for stations by name. Returns a list of up to 10 matching stations with their internal HAFAS IDs, coordinates, and available transport products. The HAFAS ID format is a complex string starting with 'A=1@O=...' that encodes station metadata.

Input
ParamTypeDescription
queryrequiredstringStation name search query (e.g., 'Berlin', 'München Hbf')
Response
{
  "type": "object",
  "fields": {
    "stations": "array of station objects with id (HAFAS ID string), extId (numeric station ID), name, lat, lon, type, and products fields"
  },
  "sample": {
    "data": {
      "stations": [
        {
          "id": "A=1@O=Berlin Hbf@X=13369549@Y=52525589@U=80@L=8011160@p=1780945770@i=U×008065969@",
          "lat": 52.524925,
          "lon": 13.369629,
          "name": "Berlin Hbf",
          "type": "ST",
          "extId": "8011160",
          "products": [
            "ICE",
            "EC_IC",
            "IR",
            "REGIONAL",
            "SBAHN",
            "BUS",
            "UBAHN",
            "TRAM"
          ]
        }
      ]
    },
    "status": "success"
  }
}

About the Bahn API

Station Search and HAFAS IDs

The get_station_autocomplete endpoint accepts a query string (e.g. 'Berlin' or 'München Hbf') and returns up to 10 matching station objects. Each object includes a full HAFAS ID — a compound string in the format A=1@O=... — alongside a numeric extId, human-readable name, lat/lon coordinates, station type, and available transport products. The HAFAS ID is required as origin_id and destination_id for connection searches, so this endpoint is the natural starting point for any journey workflow.

Connection Search and Real-Time Data

search_connections takes two HAFAS IDs and an optional ISO 8601 departure_time (defaulting to two hours from now). It returns a verbindungen array where each connection includes trip IDs, a ctxRecon token, sections detailing each leg of the journey, total duration, transfer count, train types, intermediate stops, and an angebotsPreis price field when available. The verbindungReference object in the response carries earlier and later pagination tokens so you can page through adjacent departure windows.

Ticket Offers and Metadata

Once you have a ctxRecon token from a connection result, get_ticket_offers fetches detailed fare options for that specific trip. The get_metadata endpoint requires no input and returns master reference data: traveler types (reisendenTypen, reisendenTypenAll), BahnCard discount categories (ermaessigungsArten), entry types (einstiegsTypen), and product information (produktInfo). This data is useful for building booking UIs or filtering connections by traveler profile.

Regional Transit Associations

get_transit_associations returns all known German regional transit networks (Verkehrsverbünde) with their code, kuerzel abbreviation, description, shortDescription, logo URL, and a hatShop boolean indicating whether the association has an online shop. This is useful for mapping local transit coverage alongside DB long-distance routes.

Reliability & maintenanceVerified

The Bahn API is a managed, monitored endpoint for bahn.com — not a raw scraper you maintain. Every endpoint is automatically health-checked on a schedule, and when bahn.com changes and a check fails, the API is automatically queued for repair and re-verified. It is built to keep working as the site underneath it changes.

This isn't an official bahn.com API — it's an independent, maintained REST wrapper over public data. Where the source has no official API (or only a limited one), Parse gives you a stable contract over a source that never promised one, and keeps it current. Need a new endpoint or field? You can revise it yourself in plain English and the agent rebuilds it against the live site in minutes — contributing the change back to the shared API is free.

Last verified
8h ago
Latest check
3/4 endpoints passing
Maintenance
Monitored & self-healing
Will this API break when the source site changes?+
It's built not to. Every endpoint is health-checked on a schedule with automated test probes. When the source site changes and a check fails, the API is automatically queued for repair and re-verified — that's the self-healing layer. Each API page shows when its endpoints were last verified. And because marketplace APIs are shared, any fix reaches everyone using it.
Is this an official API from the source site?+
No — Parse APIs are independent, managed REST wrappers over publicly available data. That is the point: where a site has no official API (or only a limited one), Parse gives you a maintained, monitored endpoint for that data and keeps it working as the site changes — so you get a stable contract over a source that never promised one.
Can I fix or extend this API myself if I need a new endpoint or field?+
Yes — and you don't have to wait on us. This API was generated by the Parse agent, which stays attached. Describe the change in plain English ("add an endpoint that returns reviews", "fix the price field") in the revise box on the API page or via the revise_api MCP tool, and the agent rebuilds it against the live site in minutes. Contributing the change back to the public API is free.
What happens if I call an endpoint that has an issue?+
Errors are machine-readable: a bad call returns a clean status with the list of available endpoints and a repair hint, so an agent (or you) can recover or trigger a fix instead of failing silently. Confirmed failures feed the automatic repair queue.
Common use cases
  • Build a journey planner that resolves station names to HAFAS IDs and returns timetabled connections with real-time delay data.
  • Display fare estimates for specific DB connections by chaining search_connections with get_ticket_offers.
  • Aggregate German regional transit association logos and shop links for a multi-operator travel portal.
  • Power station autocomplete inputs in travel apps using the name, coordinates, and transport products fields.
  • Page through departure windows using earlier/later tokens from verbindungReference to show rolling timetables.
  • Filter connection searches by traveler type and BahnCard discount using metadata from get_metadata.
  • Map station coordinates (lat/lon from get_station_autocomplete) to visualize Deutsche Bahn network coverage.
Pricing & limitsSee full pricing →
TierPriceCredits/monthRate limit
Free$0/mo1005 req/min
Hobby$30/mo1,00020 req/min
Developer$100/mo5,000100 req/min

One credit = one API call regardless of which marketplace API you call. Exceeding the rate limit returns a 429 response. Authenticate with the X-API-Key header.

Frequently asked questions
Does Deutsche Bahn have an official developer API?+
Yes. Deutsche Bahn publishes APIs through its RMV and DB API Marketplace at https://developers.deutschebahn.com. Those APIs have separate registration requirements and their own data models. This Parse API offers a simpler, key-based access path to the same bahn.com journey data without a separate DB developer account.
What does search_connections return beyond basic departure and arrival times?+
Each connection object in the verbindungen array includes scheduled and real-time departure/arrival times, total journey duration, number of transfers, train types per section, intermediate stops, occupancy information, and an angebotsPreis price field when pricing is available. The ctxRecon token on each connection can be passed to get_ticket_offers for detailed fare breakdowns.
What is the HAFAS ID and why do I need it?+
get_station_autocomplete returns a full HAFAS ID string (format: A=1@O=StationName@X=...) along with a shorter numeric extId. The search_connections endpoint requires the full HAFAS ID string — not the numeric extId — as its origin_id and destination_id parameters. Always use the complete string from the autocomplete response.
Does the API cover international train connections outside Germany?+
The API is scoped to Deutsche Bahn data from bahn.com, which includes some cross-border routes DB operates, but comprehensive international coverage for non-DB carriers is not currently part of these endpoints. The API covers German domestic journeys, HAFAS station lookup, DB transit associations, and pricing data for DB routes. You can fork this API on Parse and revise it to add endpoints targeting international rail operators.
Can I retrieve historical timetable data or past journeys?+
Not currently. The search_connections endpoint is oriented toward present and future departures — it defaults to two hours from now when no departure_time is supplied, and accepts future ISO 8601 timestamps. Historical schedule or booking history data is not exposed by these endpoints. You can fork this API on Parse and revise it to add a historical timetable endpoint if that data surface becomes accessible.
Page content last updated . Spec covers 5 endpoints from bahn.com.
Related APIs in TravelSee all →
bahn.de API
Access data from bahn.de.
thetrainline.com API
Search UK train stations and find the cheapest fares across date ranges, then generate direct booking links to complete your purchase on Trainline.com. Get real-time journey information to compare prices and book your tickets in seconds.
amtrak.com API
Search for Amtrak trains across stations, compare fares, and discover discounts to plan your rail journey with current pricing and availability. Get detailed train information, autocomplete station names, and find the cheapest routes for your travel dates.
trenitalia.com API
Search for trains across Italy, check real-time train status and delays, view station departure and arrival boards, and find available tickets all in one place. Get live traffic information and detailed train itineraries to plan your journey with complete visibility into schedules and service disruptions.
railyatri.in API
Search trains between stations and get real-time information including live train status, timetables, seat availability, and PNR confirmation details. Find the perfect journey by autocompleting station and train names while checking current availability and train schedules.
trainline.eu API
Search for train stations and routes across the UK and Europe, then find and compare available journeys with schedules and pricing. Book your ideal train trip by accessing real-time travel options directly from Trainline.com.
enquiry.indianrail.gov.in API
Search for trains between Indian stations, check schedules, and look up station details to plan your rail journeys. Get real-time train information with support for captcha-protected searches to ensure reliable access to Indian Railways data.
nationalrail.co.uk API
Check live train departure and arrival times at UK stations, search for specific stations, and get real-time service disruption alerts. Stay informed about rail service delays and changes to plan your journeys efficiently.