简体   繁体   中英

Python get API responses using Bearer Token

I have checked all examples but none shows endpoint like mine. How do I access API with endpoint such that:

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'])

I'm getting TypeError: 'str' object is not callable . Based on this solution , I need data but I'm not sure how I should do it with my endpoint.

Also, unsure if the bearer token is called correctly or not.

Please help. Thank you.

OK. That was silly of me. I've made changes on my code seems to work.

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)

Though I wish for cleaner code without having to write BearerAuth . Better solution is highly encouraged!

EDIT: Without using BearerAuth class.

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

I guess the problem is mixing f-string with format .

You need to use one of them:

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

or:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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