试图从Anbima API检索数据

2024-03-28 13:50:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动化一个过程,在此过程中,我必须从Anbima(巴西监管机构)下载一些巴西基金报价。我已经能够完成检索访问令牌的第一步,但我不知道如何使用令牌来发出请求。这是教程网站https://developers.anbima.com.br/en/como-acessar-nossas-apis/

我已经尝试了很多东西,但我从请求中得到的只是“无法在请求中找到所需的应用程序,由标题client_id标识。”

如果有人能分享一些光。先谢谢你

import requests
import base64
import json

requests.get("https://api.anbima.com.br/feed/fundos/v1/fundos")

ClientID = '2Xy1ey11****'
ClientSecret = 'faStF1Hc****'

codeString = ClientID + ":" + ClientSecret

codeStringBytes = codeString.encode('ascii')
base64CodeBytes = base64.b64encode(codeStringBytes)
base64CodeString = base64CodeBytes.decode('ascii')

url = "https://api.anbima.com.br/oauth/access-token"
headers = {
    'content-type': 'application/json'
    ,'authorization': f'Basic {base64CodeString}'
}
body = {
    "grant_type": "client_credentials"
}
r = requests.post(url=url, data=json.dumps(body), headers=headers, allow_redirects=True)
jsonDict = r.json()

##################
urlFundos = "https://api-sandbox.anbima.com.br/feed/precos-indices/v1/titulos-publicos/mercado-secundario-TPF"
token = jsonDict['access_token']

headers2 = {
    'content-type': 'application/json'
    ,'authorization': f'Bearer {token}'
}
r2 = requests.get(url=urlFundos, headers=headers2)
r2.status_code
r2.text

Tags: httpsbrimportcomclienttokenapijson
1条回答
网友
1楼 · 发布于 2024-03-28 13:50:37

我也有同样的问题,但今天我可以进步。我认为您需要调整标题中的一些参数。 遵循我开发的一段代码

from bs4 import BeautifulSoup

import requests

PRODUCTION_URL = 'https://api.anbima.com.br'
SANDBOX_URL = 'https://api-sandbox.anbima.com.br'
API_URL = '/feed/fundos/v1/fundos/'
CODIGO_FUNDO = '594733'

PRODUCTION = False

if PRODUCTION:
  URL = PRODUCTION_URL
else:
  URL = SANDBOX_URL

URL = URL + API_URL + CODIGO_FUNDO

HEADER = {'access_token': 'your token',
          'client_id' : 'your client ID'}


html = requests.get(URL, headers=HEADER).content

soup = BeautifulSoup(html, 'html.parser')

print(soup.prettify())

沙盒API将返回一个伪JSON。要访问生产API,您需要请求访问权限(我正在尝试这样做)

相关问题 更多 >