我正在创建一个名为 AnbimaApiClient
的类,旨在促进对 Anbima API 的数据请求(api 文档链接:https://developers.anbima.com.br/en/autenticacao/)。我已经成功地实现了一个名为 _get_new_anbima_token
的方法,它为 api 调用生成一个 access_token。问题出在 get_fidc_method
中。该函数的目标是根据唯一识别码(称为 CNPJ)提取巴西对冲基金的数据。 (这里是 API 如何提取对冲基金数据的文档链接:https://developers.anbima.com.br/en/apis-de-fundos-2/#submenu-titles-2)。
import requests as r
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
import os, json, oauthlib
class AnbimaApiClient:
__client_id = "client_id"
__client_secret = "client_secret"
__client_access_token = 'client_access_token'
__token_url = 'https://api.anbima.com.br/oauth/access-token' # token generation
__fidc_url = 'https://api.anbima.com.br/feed/fundos/v1/fundos-estruturados' # url that im trying to
# pull data from
def __init__(self):
client = BackendApplicationClient(client_id=self.__client_id)
self.oauth = OAuth2Session(client=client)
self.session = r.Session()
# setting session headers
self.session.headers.update({
'Content-Type': 'application/json',
"Authorization": f"Basic {self.__access_token}"
})
def _get_new_anbima_token(self, only_token=True):
# NOTE: This is working perfectly
token = self.oauth.fetch_token(token_url=self.__token_url,
client_id=self.__client_id,
client_secret=self.__client_secret)
if only_token:
return token['access_token']
return token
def get_fidc_data(self, field, value):
params = {
field: value
}
response = self.session.get(self.__fidc_url, params=params)
return response.text
def main():
"""
A simple test of the get_fidc_data method
"""
anbima_client = AnbimaApiClient()
data = anbima_client.get_fidc_data('cnpj_fundo', '29.494.037/0001-03')
print(data)
if __name__ == '__main__':
main()
每次我运行这个脚本时,这是response.text
的输出:
Could not find a required APP in the request, identified by HEADER client_id.
我知道 API 遵循此身份验证过程,因为它是 API 文档中所写的内容:“身份验证类型必须是‘基本身份验证’,如:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization."在标题中,但仍然没有任何效果。你们能帮帮我吗?我在这里出了什么问题?在标题中吗?非常欢迎任何帮助,谢谢大家的耐心。
答案 0 :(得分:1)
根据Anbima的网站,认证应该是base64:
"As informações passadas para o campo Authorization devem ser codificadas em base 64. Assim, para gerar o header Authorization do par client_id = aC2yaac23 e client_secret = 1bhS45TT, por exemplo, deve ser gerada a string:51byahda resultará na chave YUMyeWFhYzIzOjFiaFM0NVRU. Desta forma, o header ficaria: 'Authorization': 'Basic YUMyeWFhYzIzOjFiaFM0NVRU'"
尝试使用 base64 库:
import requests, json, base64
aut_ascii = 'client_id:client_secret' # for example "aC2yaac23:1bhS45TT"
message_bytes = aut_ascii.encode('ascii')
message_64 = base64.b64encode(message_bytes).decode('ascii')
header_aut = {"Content-Type":"application/json",
"Authorization":"Basic %s"%message_64
}
data_aut = {"grant_type":"client_credentials"}
aut = requests.post(url="https://api.anbima.com.br/oauth/access-token",headers=header_aut,data=json.dumps(data_aut),allow_redirects=True)
print(aut.content)