ガイドAPIリファレンス変更履歴
ガイド

資格情報を取得する

HERE Webサイトでプランにサインアップし、グローバル版のHERE Geocoding and Searchを使用する場合、 2つの異なる認証オプションが用意されています

使用可能な認証オプションについては「IDとアクセス管理開発者ガイド」を参照してください。

資格情報のテスト方法

以下のPythonスクリプトhgs_access_test.pyを使用して、OAuthトークン認証メソッドを使用したHERE Geocoding and Search (グローバルバージョン)へのアクセスをテストできます。

requestsパッケージとrequests_oauthlibパッケージの両方が必要です。

使用例

hgs_access_test.pycredentials.properties ファイルのアクセス キー ID とアクセス キー シークレットを取得して、「Berlin」のクエリを /geocode エンドポイントに送信します。次のような結果になります。

$ python hgs_access_test.py {YOUR_KEY_ID} {YOUR_KEY_SECRET}

(...)
send: b'POST /oauth2/token HTTP/1.1\r\nHost: account.api.here.com\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, ...
send: b'{"grantType": "client_credentials", "clientId": ...
reply: 'HTTP/1.1 200 OK\r\n'
(...)
DEBUG:urllib3.connectionpool:https://account.api.here.com:443 "POST /oauth2/token HTTP/1.1" 200 879
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): discover.search.hereapi.com:443
send: b'GET /v1/discover?at=52.521,13.3807&q=berlin HTTP/1.1\r\nHost: discover.search.hereapi.com\r\nUser-Agent: ...
reply: 'HTTP/1.1 200 OK\r\n'
(...)
DEBUG:urllib3.connectionpool:https://discover.search.hereapi.com:443 "GET /v1/discover?at=52.521,13.3807&q=berlin HTTP/1.1" 200 265
results:
{
  "items": [
    {
      "title": "Berlin, Deutschland",
      "id": "here:cm:namedplace:20187403",
      "resultType": "locality",
      "localityType": "city",
      "address": {
        "label": "Berlin, Deutschland",
        "countryCode": "DEU",
        "countryName": "Deutschland",
        "state": "Berlin",
        "county": "Berlin",
        "city": "Berlin",
        "postalCode": "10117"
      },
      "position": {
        "lat": 52.51604,
        "lng": 13.37691
      },
      "distance": 608,
      "mapView": {
        "west": 13.08835,
        "south": 52.33812,
        "east": 13.761,
        "north": 52.6755
      }
    }
  ]
}

hgs_access_test.py ソース コード

# Copyright 2019 HERE Europe B.V
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
# to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from sys import argv, stderr, exit
from json import dumps
import logging
import http.client
http.client.HTTPConnection.debuglevel = 1

logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger('requests.packages.urllib3')
requests_log.propagate = True
requests_log.setLevel(logging.DEBUG)

try:
    from requests_oauthlib import OAuth1
except ImportError as e:
    raise ImportError(f'{e.msg}\nPackage available at https://pypi.org/project/requests-oauthlib')

try:
    from requests import get, post, HTTPError
except ImportError as e:
    raise ImportError(f'{e.msg}\nPackage available at https://pypi.org/project/requests')

usage = """Usage:
    hgs_access_test.py <key-id> <key_secret>
"""

search_query = 'https://discover.search.hereapi.com/v1/discover?at=52.521,13.3807&q=berlin'

# 1. Retrieve token
try:
    data = {
        'grantType': 'client_credentials',
        'clientId': argv[1],
        'clientSecret': argv[2]
        }
except IndexError:
    stderr.write(usage)
    exit(1)

response = post(
    url='https://account.api.here.com/oauth2/token',
    auth=OAuth1(argv[1], client_secret=argv[2]) ,
    headers= {'Content-type': 'application/json'},
    data=dumps(data)).json()

try:
    token = response['accessToken']
    token_type = response['tokenType']
    expire_in = response['expiresIn']
except KeyError as e:
    print(dumps(response, indent=2))
    exit(1)

# 2. Use it in HERE Geocoding And Search query header
headers = {'Authorization': f'{token_type} {token}'}
search_results = dumps(get(search_query, headers=headers).json(), indent=2)

print(f'results:\n{search_results}')