Skip to content

Python Example

Using the MapTrip Server API requires nothing but a method to send HTTP requests and to handle JSON data. This tutorial shows how to use the API from Python code with a simple example:

Assume you have two addresses and you want to know how far it is from one of them to the other and how long it takes to go there by car.

This can be done by calculating a route with the endpoint [GET] /route of the MapTrip Server API (see endpoint and tutorial). This takes two coordinates as input, so you first have to find the coordinates for the addresses with the endpoint [GET] /geocoder. And as the API authentication is based on JWT, we will need the endpoint [GET] /authenticate as well.

To send HTTP requests, we use the Requests library which can be installed with curl pip install requests. For further information see the documentation.

Obtaining a JWT Token

If you already have a MapTrip user account, you can use the endpoint [POST] /authenticate to obtain a token to use the API.

The request is sent in the highlighted section. As this endpoint uses the HTTP method POST, the function requests.post() is called with three arguments:

  • the URL of the endpoint
  • the data to send (a JSON object with user and password)
  • two headers indicating that the format of the message body and the expected response format are JSON
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import requests
import json

data = json.dumps({
    "user": "user@example.org",
    "password": "secret"
})

headers = {
    "Content-Type": "application/json",
    "Accept": "application/json"
}

r = requests.post(url="https://api.maptrip.de/v1/authenticate",
                  data=data,
                  headers=headers)

if r.status_code == requests.codes.ok:
    result = r.json()
    token = result["token"]
    print(token)
else:
    raise Exception(f"Failed to load token, status code: {r.status_code}")

For correct user data this will obtain and print a new token. If you do not change the credentials it will raise an exception as the API will return the HTTP status code 401 Unauthorized.

For the following demos we will use a free demo token:

1
2
3
4
import requests

r = requests.get("https://api.maptrip.de/token/demo")
token = r.text

Geocoding an Address

For this example, we are not interested in the address found during geocoding and its quality, but only in the coordinate. The following function sends a string with an address to the endpoint [GET] /geocoder and checks if the request was successful and an address was found. If so, this is returned, otherwise the value None.

The request looks very similar to the first one, but this is a GET request, so there is no message body but parameters. For this reason, no Content-Type needs to be specified. Instead, the request must contain the header Authorization with the word Bearer and the token we queried before.

 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def geocode(address):
    headers = {
        "Accept": "application/json",
        "Authorization": "Bearer " + token
    }

    params = {
        "provider": "TomTom",
        "address": address
    }

    r = requests.get("https://api.maptrip.de/v1/geocoder",
                     params=params,
                     headers=headers)

    if r.status_code == requests.codes.ok:
        result = r.json()
        if len(result) == 1:
            return result[0]["address"]["coordinate"]

    return None

To test the function you can call it with an address string:

>>> print(geocode("Weiherstr. 38, Bonn"))
{'lat': 50.7365574, 'lon': 7.0919497}

Calculating a Route

This is the most simple kind of route you can calculate: We do not use via points, traffic information, vehicle types and attributes and so on, just the start and destination.

As the coordinates for the parameters from and to have to be provided as strings, we use a helper function to format them.

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def coordinate_to_text(coordinate):
    return f"{coordinate['lat']},{coordinate['lon']}"


def route(start, destination):
    headers = {
        "Accept": "application/json",
        "Authorization": "Bearer " + token
    }

    params = {
        "provider": "TomTom",
        "from": coordinate_to_text(start),
        "to": coordinate_to_text(destination)
    }

    r = requests.get("https://api.maptrip.de/v1/route",
                     params=params,
                     headers=headers)

    if r.status_code == requests.codes.ok:
        return r.json()

    return None

Putting all this together, we can write code to geocode two addresses, check if both were found, calculate a route between them, and output the desired output.

start = geocode("Weiherstr. 38, Bonn")
destination = geocode("Köln")

if start is not None and destination is not None:
    routes = route(start, destination)
    if routes is not None and len(routes) > 0:

        driving_time_in_seconds = routes[0]["summary"]["drivingTime"]
        length_in_meters = routes[0]["summary"]["length"]

        driving_time = "{:.1f}".format(driving_time_in_seconds / 60)
        length = "{:.1f}".format(length_in_meters / 1000)

        print(f"The route is {length} km long and takes {driving_time} minutes")
    else:
        print("Failed to calculate route")
else:
    print("Failed to geocode addresses")