基于Mozilla身份验证使用python发出API请求

2024-09-28 03:13:46 发布

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

我正在创建一个名为AnbimaApiClient的类,旨在促进Anbima API的数据请求(API文档链接:https://developers.anbima.com.br/en/autenticacao/)。我成功地实现了一个名为_get_new_anbima_token的方法,该方法为api调用生成一个访问令牌。问题出在get_fidc_method。此功能的目标是根据unioque识别码(称为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."我试着在标题中以auth的形式传递客户端id,但仍然没有任何效果。你们能帮我吗?我这里出了什么问题?标题中有什么?欢迎提供任何帮助,谢谢大家的耐心


Tags: httpsbrimportselfcomclienttokenapi
1条回答
网友
1楼 · 发布于 2024-09-28 03:13:46

根据Anbima的网站,认证应采用base64:

“根据em base 64中的信息,通过campo授权进行编码。AASM,PARA GEAR O标题授权做PAR clitTydID=AC2YAAC23 e秘密=1BHS45 TT,POR示例,deve ser gerada A BASE64 DA串AC2YAAC23:1BHS45 TT,QueRealTaulaNa CHAVY YUMYYWHZIZOJAFFAFM0NVRU。Desta forma,o header ficaria:“授权”:“基本Yumeywfhyzizojfiafm0nvru”

尝试使用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)

相关问题 更多 >

    热门问题