【问题标题】:How to Generate API Token Using Requests如何使用请求生成 API 令牌
【发布时间】:2019-04-25 07:08:13
【问题描述】:

我正在尝试向 local real estate website 发出 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 cmets 将数据更改为字典并更改“范围”。我看到 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)

【问题讨论】:

    标签: python api oauth-2.0 python-requests


    【解决方案1】:

    docs 可以看出data 需要是dict。您将其作为包含字符串的set

    试试

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

    【讨论】:

    • 已更改为字典,但仍然收到相同的错误。我看到客户端需要按照 API 文档进行 base64 编码。我相信我已经做到了,但仍然收到 400 错误
    猜你喜欢
    • 1970-01-01
    • 2018-02-06
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2020-04-02
    • 2013-04-25
    相关资源
    最近更新 更多