Bahn APIbahn.com ↗
Access Deutsche Bahn station search, train connections, real-time schedules, ticket offers, and regional transit associations via the bahn.com API.
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.
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'
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")
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.
| Param | Type | Description |
|---|---|---|
| queryrequired | string | Station name search query (e.g., 'Berlin', 'München Hbf') |
{
"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.
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.
Will this API break when the source site changes?+
Is this an official API from the source site?+
Can I fix or extend this API myself if I need a new endpoint or field?+
What happens if I call an endpoint that has an issue?+
- 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.
| Tier | Price | Credits/month | Rate limit |
|---|---|---|---|
| Free | $0/mo | 100 | 5 req/min |
| Hobby | $30/mo | 1,000 | 20 req/min |
| Developer | $100/mo | 5,000 | 100 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.
Does Deutsche Bahn have an official developer API?+
What does search_connections return beyond basic departure and arrival times?+
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?+
Can I retrieve historical timetable data or past journeys?+
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.