使用 python-请求从 DHL 获取跟踪详细信息

Using python-requests to get tracking details from DHL

我正在尝试创建一个脚本来获取我们公司通过 DHL API 发送的所有订单的所有跟踪详细信息 API。

我尝试执行以下脚本来连接到 DHL API。

import requests
import json
import http.client

# Replace with the correct URL
url = "https://api-eu.dhl.com/track/shipments?trackingNumber=*************&requesterCountryCode=DE&originCountryCode=DE&language=en"
headers = {
'Accept': 'application/json',
'DHL-API-Key': '*********'
        }
#connection = http.client.HTTPSConnection("https://api-eu.dhl.com")

myResponse = requests.get(url, headers)

if(myResponse.ok):
 to fetch binary content
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print (key + " : " + jData[key])
else:
  with description
    myResponse.raise_for_status()

但是显示以下错误,

Traceback (most recent call last):
  File "/Users/sand/Documents/DHL Python.py", line 28, in <module>
    myResponse.raise_for_status()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py", line 940, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api-eu.dhl.com/track/shipments?trackingNumber=***************&requesterCountryCode=DE&originCountryCode=DE&language=en

所以我想澄清一下,

连接到 DHL tracking 我们需要做哪些事情API?

我已经在 DHL 开发门户创建了一个帐户并填写了详细信息,对于 select API 部分我只能 select 2,当我 selecting 其他 API 然后它显示为 Ïn Progress", 所以我删除了它。

我得到了 "consumer Key" 和 "Consumer secret",从哪里可以得到令牌,或者这足以连接 API?

除此之外我还需要做任何其他设置,因为我是新手,任何建议都会有很大帮助。

单击隐藏使用者密钥的星号下方的显示 link。消费者密钥 == 'DHL-API-Key' 出现。


Question: get tracking details from DHL - do i need to do any other settings


From python-requests.org quickstart:

使用 requests 而不是给定 DHL - Simple Python code sample 中的 http.client 你必须这样做:

import requests
url = "https://api-eu.dhl.com/track/shipments"

headers = {
    'Accept': 'application/json',
    'DHL-API-Key': 'ApiKeyHere'
    }
payload = {
    'trackingNumber': '7777777770',
    'service': 'express'
}

# This url is for testing 
url = 'https://httpbin.org/get'
resp = requests.get(url, params=payload, headers=headers)

print(resp.content)

Output: resp.content

{
  "args": {
    "service": "express", 
    "trackingNumber": "7777777770"
  }, 
  "headers": {
    "Accept": "application/json", 
    "Accept-Encoding": "gzip, deflate", 
    "Dhl-Api-Key": "ApiKeyHere", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0"
  }, 
  "origin": "54.224.8.86, 54.224.8.86", 
  "url": "https://httpbin.org/get?trackingNumber=7777777770&service=express"
}

测试 Python 3.6 - python-requests/2.22.0