首页 > 解决方案 > 使用 Token 使用 Python 调用 API

问题描述

我正在尝试使用访问令牌调用 API。

目前我得到的令牌是这样的:

import requests

auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"

data = {
    "grant_type": grant_type,
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": scope
    }

auth_response = requests.post(auth_url, data=data)

print(auth_response.content)

这会产生如下内容:

{"access_token":"eyJhbGdiOihSUzh1NhIsImtpZCI6IjlVUHVwYnBkTXN2RDZ0Ry1ZcDVRUlEiLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE2MzM4OTcxNDIsImV4cCI6hTYzMhkwMDc0MiwiaXNzIjoiaHR0cHM6Ly9vYXV0aC56YW1iaW9uLmNvbSIsImF1ZCI6ImFwaTEiLCJjbGllbnRfaWQiOiIwN0I3RkZEOC1GMDJCLTRERDAtODY2OS0zRURBNzUyRTMyNkQiLCJzY29wZSI6WyJhcGkxIl19.GU6lynvQYAAmycEPKbLgHE-Ck189x-a-rVz6QojkBIVpSLu_sSAX2I19-GlTjVWeLKoMVxqEfVq_qIaaQYa5KFmMLHRxP6J-RUgGK8f_APKjX2VNoMyGyAbZ0qXAJCvUTh4CPaRbZ6pexEishzr4-w3JN-hJLiv3-QH2y_JZ_V_KoAyu8ANupIog-Hdg8coI3wyh86OeOSAWJA1AdkK5kcuwC890n60YVOWqmUiAwPRQrTGh2mnflho2O3EZGkHiRPsiJgjowheD9_Wi6AZO0kplHiJHvbuq1PV6lwDddoSdAIKkDscB0AF53sYlgJlugVbtU0gdbXjdyBZvUjWBgw","expires_in":3600,"token_type":"Bearer","scope":"api1"}

现在我想调用 API 并在标头中传递令牌,但我不确定如何执行此操作,并且我在在线资源中进行了几次访问

我的尝试之一是:

url = "https://anotherurl.com/api/SecuredApi/StaffDetails"

head = {'Authorization': 'token {}'.format(auth_response)}
response = requests.get(url, headers=head)

print(response)

但这给了我一个 403 错误

请帮助我指出我的错误

编辑:

感谢@RaniSharim,我做了一些改变。我现在有

import requests
import json

auth_url = "https://oauth.thegivenurl.com/connect/token"
client_id = "SomeClient_ID"
client_secret = "SomeClient_Secret"
scope = "SomeScope"
grant_type = "client_credentials"

data = {
    "grant_type": grant_type,
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": scope
    }

dateparams = {
"StartDateTime": "2021-01-01 00:00:00", 
"EndDateTime" : "2021-10-11 23:59:00"
}

auth_response = requests.post(auth_url, data=data)

# print(auth_response.content)

authjson = auth_response.content
authdata = json.loads(authjson)
token = (authdata['access_token'])

# print(token)

head = {"Authorization": "Bearer " + token}
response = requests.get(url, headers=head, params=dateparams)

print(response.content)

这看起来更好,但我现在收到 400 错误:

"message":"The date range you have specified is in an invalid format. The required format is yyyy-MM-dd HH:mm:ss","status":400}

尽我所能看到我的日期范围已经是请求的格式,如下所示:

dateparams = {
"StartDateTime": "2021-01-01 00:00:00", 
"EndDateTime" : "2021-10-11 23:59:00"
}

标签: pythonapi

解决方案


通常,400 表示前端错误,但是当您执行 GET 请求时

dateparams = {
"StartDateTime": "2021-01-01 00:00:00", 
}
r = requests.get(url, params=dateparams)

print(r.url)

GET url 会变成这样:

https://oauth.thegivenurl.com/connect/token?StartDateTime=2021-01-01+00%3A00%3A00

见str

2021-01-01+00%3A00%3A00

因此,如果后端无法正确处理此问题,您也会收到此错误

但您可以通过另一种方式使用 GET:

requests.get(url, json=dateparams)

这将完美地发送您的 json 参数


推荐阅读