python - 如何使用请求生成 API 令牌
问题描述
我正在尝试向本地房地产网站发出 API 请求
我需要获取一个 oauth2 令牌,然后使用它来发出请求。不幸的是,运行以下代码时出现 400 错误。我假设请求 url 不正确,但似乎无法得到它。谢谢
import requests
import json
token_url = "https://auth.domain.com.au/v1/connect/token"
client_id = '<client_id>'
client_secret = '<client_secret>'
data = {'grant_type=client_credentials&scope=api_agencies_read%20api_listings_read'}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print(access_token_response)
编辑:
根据@aydow 评论将数据更改为字典并更改“范围”。我看到 API 文档要求对 client_id 和 client_secret 进行 base64 编码。更新了代码,它现在可以正常工作
import requests
import json
from requests.auth import HTTPBasicAuth
token_url = "https://auth.domain.com.au/v1/connect/token"
client_id = '<client_id>'
client_secret = '<client_secret>'
payload = {'grant_type': 'client_credentials','scope': 'api_agencies_read%20api_listings_read'}
headers = {"Content-Type" : "application/x-www-form-urlencoded"}
access_token_response = requests.post(token_url, auth=HTTPBasicAuth(client_id, client_secret), data=payload, headers=headers)
print(access_token_response)
解决方案
从文档中,您可以看到data
需要是dict
. 你有它作为一个set
包含一个字符串。
尝试
data = {
'grant_type': 'client_credentials',
'scope': 'api_agencies_read%20api_listings_read'
}
推荐阅读
- python - `list(itertools.groupy)` 的违反直觉的行为
- delphi - Delphi 7 颜色编码
- php - Symfony 4 - 必须配置路径“beelab_tag”处的子节点“tag_class”
- swift - 匹配集合中的元素,不同类型,公共元素
- c# - 标签在将其归为父母后消失
- python - OrientDB Gremlin 服务器在 python 中不工作
- mysql - 我不知道如何在 Laravel 中将表连接到另一个表
- android - SetClipToOutline 不适用于 RecyclerView
- c# - 应该添加到列表开头的简单 C# 节点列表函数不能用作外部静态 Void
- keras - 在定义新的损失函数时为 keras 中的张量赋值