Skip to content

Instantly share code, notes, and snippets.

@shamilnabiyev
Last active May 5, 2024 19:34
Show Gist options
  • Save shamilnabiyev/b42ba719b69bd8d6a4cffc4cfac78676 to your computer and use it in GitHub Desktop.
Save shamilnabiyev/b42ba719b69bd8d6a4cffc4cfac78676 to your computer and use it in GitHub Desktop.
Get Berlin S-Bahn Lines and Station IDs from VBB Verkehrsverbund Berlin-Brandenburg
import json
import requests
import pandas as pd
from itertools import chain
def get_sbahn_list(product='suburban', operator='1'):
"""
Get S-Bahn Line list from VBB Transport API
S-Bahn: product=suburban
S-Bahn Berlin GmbH: operator=1
More details on API Docs: https://v6.vbb.transport.rest/api.html
"""
api_endpoint = f'https://v6.vbb.transport.rest/lines?product={product}&operator={operator}'
with requests.Session() as session:
req = session.get(api_endpoint)
sbahn_json = req.json()
return sbahn_json
def flatten_chain(nested):
"""
Flatten a given nested list of lists
"""
return list(chain.from_iterable(nested))
def get_stop_id_list(item):
"""
Extract unique Stop Location IDs
"""
stop_list = list(map(lambda x: x["stops"], item["variants"]))
stop_list = flatten_chain(stop_list)
stop_list = set(stop_list)
return list(stop_list)
def get_station_dhid(item, delimiter=":"):
"""
Extract Station ID (DHID) from a given Stop Location ID
DHID: <Landeskennzeichen(LK)>:<Kreisschlüssel(KS)>:<Lokale Haltestellen ID>:<Bereich-ID>:<Mast-ID>:<Halteposition>
"""
x = str(item).split(delimiter)
if len(x) < 3:
return item
return f"{x[0]}:{x[1]}:{x[2]}"
if __name__ == "__main__":
sbahn_json = get_sbahn_list()
sbahn_stops_all = list(map(lambda x: get_stop_id_list(x), sbahn_json))
sbahn_stops_all = flatten_chain(sbahn_stops_all)
sbahn_stops_all = list(set(sbahn_stops_all))
print("Num. S-Bahn Stops in Belin:", len(sbahn_stops_all))
sbahn_stations = list(map(lambda x: get_station_dhid(x), sbahn_stops_all))
sbahn_stations = list(set(sbahn_stations))
print("Num. S-Bahn Stations in Berlin:", len(sbahn_stations))
@shamilnabiyev
Copy link
Author

U-Bahn / Subway

https://v6.bvg.transport.rest/

U-Bahn: product=subway
Berliner Verkehrsbetriebe (BVG): operator=796

@shamilnabiyev
Copy link
Author

Get U-Bahn (Subway) Stops only:

curl https://v6.vbb.transport.rest/stops/900100003/arrivals?duration=10&subway=true&suburban=false&tram=false&bus=false&ferry=false&express=false&regional=false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment