首页 > 解决方案 > 如何使用请求生成 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)

标签: pythonapioauth-2.0python-requests

解决方案


文档中,您可以看到data需要是dict. 你有它作为一个set包含一个字符串。

尝试

data = {
    'grant_type': 'client_credentials',
    'scope': 'api_agencies_read%20api_listings_read'
}

推荐阅读