不允许AMBIMA api请求方法

问题描述 投票:0回答:1

我正在尝试访问 AMBIMA API,但是根据如何分页,我需要来自身份验证 API 的令牌。我已按照身份验证页面的说明进行操作并得到了响应,但是应该有令牌的地方出现消息“不允许的方法”。

如何翻页:https://developers.anbima.com.br/pt/documentacao/visao-geral/como-acessar-nossas-apis/ 身份验证页面:https://developers.anbima.com.br/pt/documentacao/visao-geral/autenticacao/#oauth2

我使用的代码:

 url = "https://api.anbima.com.br/oauth/access-token"
 header = {
 "Content-Type": "application/json",
 "Authorization": "Basic base64(my_id:my_access)",
 }
 
 response = requests.get(url, header)
 infos = response.json()

结果:

{'timestamp': 1714681762294, 'status': 405, 'error': 'Method Not Allowed'}

我尝试将

requests.get()
更改为
requests.post()
并将行
"grant_type": "client_credentials"
添加到字典中,但两者都返回不同的错误。我能做什么?

python api
1个回答
0
投票

您需要调用 POST 而不是 GET。

演示

另存为

demo.py

import requests
from requests.auth import HTTPBasicAuth
import json

def get_access_token(client_id, client_secret):
    url = "https://api.anbima.com.br/oauth/access-token"
    headers = {
        'Content-Type': 'application/json'
    }
    data = {
        "grant_type": "client_credentials"
    }
    
    # Using HTTPBasicAuth to handle the Basic Auth header
    response = requests.post(url, headers=headers, json=data, auth=HTTPBasicAuth(client_id, client_secret))
    
    if response.status_code == 200:
        return response.json()  # Returns the JSON response if successful
    else:
        return response.status_code, response.text  # Returns error status and message if not successful

# Example usage:
client_id = 'your_client_id_here'
client_secret = 'your_client_secret_here'
token_response = get_access_token(client_id, client_secret)
print(token_response)

运行它

python demo.py

结果

enter image description here

邮递员

网址

POST https://api.anbima.com.br/oauth/access-token

体内

{
    "grant_type": "client_credentials"
}

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.