如何使用请求生成API令牌

时间:2018-07-19 00:55:29

标签: python api oauth-2.0 python-requests

我正在尝试向local real estate website发出API请求

我需要获取一个oauth2令牌,然后使用该令牌进行请求。不幸的是,运行以下代码时出现400错误。我假设请求网址不正确,但似乎无法获取。谢谢

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)

1 个答案:

答案 0 :(得分:0)

docs中,您可以看到data必须是dict。您将其作为包含字符串的set

尝试

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