python_mvg_api – Munich Public Transport made simple

Intro

Not too long ago, MVG (aka Münchner Verkehrsgesellschaft) relaunched their Website, which now actually utilizes a JSON api! (I know, crazy, right?) This python module tries to provide easy to use access to most aspects of the mvg api.

It offers:

  • The next departures for any station in the MVV
    • This includes S-Bahn and Schienenersatzverkehr
  • Listing nearby stations based on geolocation
  • Search for Stations and POI
  • Routing
  • Current warnings about service interruptions

Take a look at example.py, it shows some basic concepts, or at the rest of the docs, where everything should be adequately documented.

Note on the usage policy

From https://www.mvg.de/impressum.html:

[...] Die Verarbeitung unserer Inhalte oder Daten durch Dritte erfordert unsere ausdrückliche Zustimmung. Für private, nicht-kommerzielle Zwecke, wird eine gemäßigte Nutzung ohne unsere ausdrückliche Zustimmung geduldet. Jegliche Form von Data-Mining stellt keine gemäßigte Nutzung dar.[...]

In other words: Private, noncomercial, moderate use of the API is tolerated. They don’t consider data mining as moderate use.

(Disclaimer: I am not a lawyer, this isn’t legal advice)

Module documentation

exception mvg_api.ApiError(code, reason)

Some error was returned by the mvg api when handling the request. :ivar code: status code returned by the API :ivar reason: response given by the api (optional)

class mvg_api.Station(station)

Gives you a proxy to get the next departures for a particular station.

Either give it an exact station name (like “Hauptbahnhof”) or a station_id.

Deprecated-ish: This is not really all that useful. Just using get_id_for_station() and get_departures() really is the nicer way in most cases.

mvg_api.get_departures(station_id, timeoffset=0)

Get the next departures for station_id. Optionally, define timeoffset to not show departures sooner than a number of minutes.

Change in 1.2.2: accepts both ‘old-style’ integer IDs which were used by the API before this version and the new string IDs which look like de:09162:6.

To get the station_id associated with a station name, use get_id_for_station().

Returns a list like:

[
    {
        'departureTime': 1571923180000,
        'product': 'UBAHN',
        'label': 'U2',
        'destination': 'Messestadt Ost',
        'live': True,
        'lineBackgroundColor': '#dd3d4d',
        'departureId': 1152101303,
        'sev': False,
        'departureTimeMinutes': 0
    },
]

departureTimeMinutes, the time left to the departure in minutes, is added to the response from the api for your convenience.

mvg_api.get_id_for_station(station_name)

Returns the station_id for the given station name.

If more than one station match, the first result is given. None is returned if no match was found.

mvg_api.get_lines(station_id)

Get the lines being served for station_id.

Change in 1.2.2: accepts both ‘old-style’ integer IDs which were used by the API before this version and the new string IDs which look like de:09162:6.

To get the station_id associated with a station name, use get_id_for_station().

Returns a list like:

[
    {
        "destination" : "Aying",
        "sev" : false,
        "partialNet" : "ddb",
        "product" : "SBAHN",
        "lineNumber" : "S7",
        "divaId" : "92M07"
    },
]

Note: The api seemingly only returns a single object per line served, meaning that both directions of a line are represented only by a single line in the response.

mvg_api.get_locations(query)

Returns all matches from the search for the given query string.

query can either be a name of a station or of a street, square, etc.

Returns a list wich looks somewhat like this:

[
    {
        'type': 'station',
        'latitude': 48.12046,
        'longitude': 11.61869,
        'id': 'de:09162:1060',
        'place': 'München',
        'name': 'Innsbrucker Ring',
        'hasLiveData': True,
        'hasZoomData': True,
        'products': ['UBAHN'],
        'aliases': 'Muenchen Munchen',
        'link': 'IR',
        'lines': {
            'tram': [],
            'nachttram': [],
            'sbahn': [],
            'ubahn': [],
            'bus': [],
            'nachtbus': [],
            'otherlines': []
        }
    },
]
mvg_api.get_nearby_stations(lat, lon)

Stations nearby the given location.

Parameters:
  • lat (float) – Latitude
  • lon (float) – and longitude of the desired location.

Returns a list which is formated in this fassion:

[
    {
        'type': 'station',
        'latitude': 48.12046,
        'longitude': 11.61869,
        'id': 'de:09162:1060',
        'place': 'München',
        'name': 'Innsbrucker Ring',
        'hasLiveData': True,
        'hasZoomData': True,
        'products': ['UBAHN'],
        'aliases': 'Muenchen Munchen',
        'link': 'IR',
        'lines': {
            'tram': [],
            'nachttram': [],
            'sbahn': [],
            'ubahn': [],
            'bus': [],
            'nachtbus': [],
            'otherlines': []
        }
    },
 ]
mvg_api.get_route(start, dest, time=None, arrival_time=False, max_walk_time_to_start=None, max_walk_time_to_dest=None, change_limit=None, ubahn=True, bus=True, tram=True, sbahn=True)

Plans a route from start to dest

Change in 1.2.2: accepts both ‘old-style’ integer IDs which were used by the API before this version and the new string IDs which look like de:09162:6.

Parameters:
  • start (int/str/tuple) – The station_id of the starting station or a tuple of coordinates
  • dest (int/str/tuple) – station_id of the destination station or a tuple of coordinates
  • time (datetime, optional) –
  • arrival_time (bool, optional) – Specifies if time is the starting time (which is default) or the desired time of arrival.
  • max_walk_time_to_dest (max_walk_time_to_start,) – Maximum time of walking in minutes required to reach the start/dest.
  • changeLimit (int, optional) – Specifies the maximum amount of changes.
  • ubahn (bool, optional) – Specifies if the subway(UBahn) should be considered in the route
  • bus (bool, optional) – Specifies if the bus should be considered in the route
  • tram (bool, optional) – Specifies if the tram should be considered in the route
  • sbahn (bool, optional) – Specifies if the SBahn should be considered in the route
mvg_api.get_stations(station)

Like get_locations(), but filters out all results which are not stations.

Indices and tables