繁体   English   中英

Python 使用承载令牌获取 API 响应

[英]Python get API responses using Bearer Token

我检查了所有示例,但没有一个显示像我这样的端点。 如何使用以下端点访问 API :

end_point = f"https://something.com/version/input1/{0}/input2/{1}".format(payload["input1"], payload["input2"])

api_token = {"authorization": "Bearer LonGTokEN"}
    
api_response = requests.post(url=end_point, auth=api_token['authorization'])

我收到TypeError: 'str' object is not callable 基于这个解决方案,我需要data ,但我不确定我应该如何使用我的端点。

此外,不确定是否正确调用了不记名令牌。

请帮忙。 谢谢你。

好的。 我真傻。 我对我的代码进行了更改似乎有效。

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

def test_api_no_pax(mock_input, expected_output):
    """
    Testing API after deployment (no pax)
    """
    with open(f"./assets/{mock_input}.json") as json_file:
        payload = json.load(json_file)

    end_point = "https://something.com/version/input1/{0}/input2/{1}".format(payload["input1"], payload["input2"])

    api_token = {"authorization": "LonGTokEN"} # removed Bearer since I use BearerAuth

    api_response = requests.get(url=end_point, auth=BearerAuth(api_token['authorization']))
    print(api_response.text)

尽管我希望无需编写BearerAuth就能获得更简洁的代码。 强烈鼓励更好的解决方案!

编辑:不使用BearerAuth class。

api_token = {"authorization": "Bearer LonGTokEN"}
api_response = requests.get(url=end_point, headers=api_token)

我想问题是将f-stringformat混合。

您需要使用其中之一:

end_point = "https://something.com/version/input1/{0}/input2/{1}".format(payload["input1"], payload["input2"])

或者:

end_point = f"https://something.com/version/input1/{payload['input1']}/input2/{payload['input2']}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM