无法对矩阵路由API上的异步请求进行身份验证

2024-06-25 23:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有效的HereMaps API密钥,我正在使用python requests库执行对链接的GET请求,该请求在进行异步调用后返回。我试着这样执行它:

https://aws-ap-southeast-1.matrix.router.hereapi.com/v8/matrix/01187ff8-7888-4ed6-af88-c8f9be9242d7/status?apiKey={my-api-key}

尽管我在生成上述链接之前提供了正确的密钥,但上述请求的结果返回:

{
  "error": "Unauthorized",
  "error_description": "No credentials found"
}

我们应该如何通过身份验证来检查Matrix Routing v8 API上异步请求的状态结果


Tags: httpsawsapiget链接密钥errorrequests
2条回答

请检查documentation for the domain name to use for HERE services。对于矩阵路由,您应该使用matrix.route.ls.hereapi.com

披露:我是HERE Technologies的产品经理

有两种身份验证方法available to you for using HERE APIs:API密钥和OAuth令牌

由于凭据的处理方式,当您发出异步请求时,您需要在使用API密钥时禁用自动客户端重定向,因为客户端不会将apiKey参数再次添加到已重定向到的URL

在使用Python和requests时,有许多解决方案,下面是一个完整的示例,可能会有所帮助:

import requests, time

api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# "Profile mode (car fastest)" example request
request = {
    "origins": [{"lat": 52.5309, "lng": 13.3849}, {"lat": 54.0924, "lng": 12.0991}],
    "destinations": [
        {"lat": 51.3397, "lng": 12.3731},
        {"lat": 51.0504, "lng": 13.7373},
    ],
    "regionDefinition": {"type": "world"},
    "profile": "carFast",
}

# Using a Session object allows you to persist certain parameters accross requests
# see: https://requests.readthedocs.io/en/master/user/advanced/
session = requests.Session()
# Add `?apiKey=xxxxxx` to all requests
session.params = {"apiKey": api_key}
# Raise an exception for any non 2xx or 3xx HTTP return codes
session.hooks = {"response": lambda r, *args, **kwargs: r.raise_for_status()}

# Send an asynchronous request, see: https://developer.here.com/documentation/matrix-routing-api/8.3.0/dev_guide/topics/get-started/asynchronous-request.html
status_response = session.post(
    "https://matrix.router.hereapi.com/v8/matrix", json=request
).json()

# Polling for the job status for 100 times
# You might want to use exponential back-off instead of time.sleep
for _ in range(0, 100):
    # do not follow the redirect here
    status_response = session.get(
        status_response["statusUrl"], allow_redirects=False
    ).json()

    if status_response["status"] == "completed":
        # download the result
        matrix_response = session.get(status_response["resultUrl"]).json()
        print(matrix_response)
        break
    elif status_response["accepted"] or status_response["inProgress"]:
        continue
    else:
        print(f"An error occured: {status_response}")
        break
    time.sleep(0.5)  # sleep for 500 ms

免责声明:我在这里从事矩阵路由技术的工作

相关问题 更多 >