GuidesAPI Reference
Guides

How to get an OAuth 2.0 token with Python

To use OAuth 2.0 token authentication, your app must be able to obtain OAuth 2.0 Token Credentials for each request to a HERE service. In this tutorial, you learn how to acquire a HERE OAuth 2.0 bearer token using Python.

Prerequisites

Code an OAuth 2.0 token request

If using OAuth 2.0 token authentication, you must enable your app to obtain token credentials for each request to a HERE service.

To accomplish this, you can do one of the following:

HERE provides REST APIs to provide secure access tokens for authenticated API calls by your app. Tokens are usable for up to 24 hours after creation.

Steps

Step 1 - Register your app

You must register your app to generate an access key ID an access key ID and access key secret, which are required to obtain a token.

For more information, see Register your app and get credentials. The following is an example of a client.credentials file.

here.user.id = HERE-83f93718-8856-4239-9b1e-7b930915876b
here.client.id = wAT7An4k4ypVlLimnq8O
here.access.key.id = wUr2KJHDJkN2WMYwrl_fDA
here.access.key.secret = WDC4YqoQMFbhozEF7r7ccwZSYWHBtYORoIAmRBARvQip_eOS1VUshGUQmTw8j5R552OVW0kVTcpoLB8BjdMkIQ
here.token.endpoint.url = https://account.api.here.com/oauth2/token

Step 2 - Create an OAuth 2.0 signature and request a token

When requesting a token, you must pass the OAuth signature in the Authorization Header of a request. This signature helps in authenticating a user or an app. First, create a parameter string containing the following six key-value pairs.

Note that you must create a new signature for each token request to the Authentication and Authorization API. You can only use signatures once.

Credentials file To get your credentials file, see OAuth 2.0 tokens. The following credentials are in this file:

CredentialDescription
grant_typeIn each file, this value is always client_credentials
oauth_consumer_keyThe Access Key ID value acquired from the credentials.properties file after generating HERE credentials.
oauth_nonceA unique string which never repeats.
oauth_signature_methodThis should always be HMAC-SHA256.
oauth_timestampThe current time, or more specifically, the number of seconds that have elapsed since the Unix epoch.
oauth_versionThis should always be 1.0.

Request

In your IDE, create a Python file and add the following code to it. Be sure to replace your oauth_consumer_key with the Access Key ID value found in the client_credentials file that you downloaded from the HERE platform.

The code block demonstrates authenticating with an API, and performs a search for the Curry Inn in Berlin, Germany.

  • To start, the code uses OAuth 2.0 authentication to obtain an access token, and then uses the token to make a POST request to a specific API endpoint.
  • With import, the code imports the requests library and OAuth1 from requests_oauthlib.
  • An OAuth1 object is then created with client_key and client_secret using key_id and key_secret, respectively, and specifies the signature_type as 'auth_header'.
  • Then, a POST request is made to https://account.api.here.com/oauth2/token with grant_type set to 'client_credentials', using the oauth object for authentication and setting the Content-Type header to 'application/x-www-form-urlencoded'.
  • Next, the access token is extracted from the JSON response using r.json()['access_token'].
  • A requests.Session object is created, and its headers include the Authorization header with the Bearer token and Content-Type as 'text/plain'.
  • Finally, a GET request is made to https://discover.search.hereapi.com/v1/discover.
import requests
from requests_oauthlib import oauth2

oauth = OAuth1(client_key=key_id, client_secret=key_secret, signature_type='auth_header')
r = requests.post('https://account.api.here.com/oauth2/token',data=dict(grant_type='client_credentials'), auth=oauth,
                  headers={'Content-Type' : 'application/x-www-form-urlencoded'})

access_token = r.json()['access_token']


s = requests.Session()
s.headers = {'Authorization': f"Bearer {access_token}",
             'Content-Type': 'text/plain'}
 
params = dict(at='52.5228,13.412', q='restaurant', limit=1)
r = s.get('https://discover.search.hereapi.com/v1/discover', params=params)
print(r.json())

Response

The following code block lists the example response after executing the previous request for the Curry Inn in Berlin, Germany. The returned JSON object provides comprehensive information about the restaurant, including its location, type, and operational details.

{
'items': [{'title': 'Curry Inn',
   'id': 'here:pds:place:276u33dc-a56607ef6101420ff5ea793cdc5c6cfe',
   'language': 'de',
   'ontologyId': 'here:cm:ontology:restaurant',
   'resultType': 'place',
   'address': {'label': 'Curry Inn, Karl-Liebknecht-Straße, 10178 Berlin, Deutschland',
    'countryCode': 'DEU',
    'countryName': 'Deutschland',
    'stateCode': 'BE',
    'state': 'Berlin',
    'countyCode': 'B',
    'county': 'Berlin',
    'city': 'Berlin',
    'district': 'Mitte',
    'street': 'Karl-Liebknecht-Straße',
    'postalCode': '10178'},
   'position': {'lat': 52.52298, 'lng': 13.41134},
   'access': [{'lat': 52.52328, 'lng': 13.41118}],
   'distance': 49,
   'categories': [{'id': '100-1000-0009', 'name': 'Fastfood', 'primary': True},
    {'id': '100-1000-0003', 'name': 'Schnellrestaurant/Lieferservice'}],
   'references': [{'supplier': {'id': 'yelp'},
     'id': 'Ix4qi3rQxTZv8GfhsNKN1A'}],
   'foodTypes': [{'id': '202-000', 'name': 'Indisch', 'primary': True}],
   'openingHours': [{'categories': [{'id': '100-1000-0003'}],
     'text': ['Mo: 10:00 - 24:00',
      'Di-Sa: 00:00 - 02:00, 10:00 - 24:00',
      'So: 00:00 - 02:00, 10:00 - 23:30'],
     'isOpen': False,
     'structured': [{'start': 'T100000',
       'duration': 'PT16H00M',
       'recurrence': 'FREQ:DAILY;BYDAY:MO,TU,WE,TH,FR,SA'},
      {'start': 'T100000',
       'duration': 'PT13H30M',
       'recurrence': 'FREQ:DAILY;BYDAY:SU'}]}]}]
}

Additional references

For more information, see: