1

I'm setting up a small Python script so my colleagues can collect data from a certain internal API based on a few inputs using the following code:

url = "https://....."
params = dict(...)
client = BackendApplicationClient(client_id=client_id)
client.prepare_request_body(scope=[])
session = OAuth2Session(client=client)
response = session.get(url=url, params=params, verify=session.verify)

where the params are based on the manual inputs. I can guarantee some of the inputs will not conform to the API's requirements fully (like lower case letters where upper case is needed, etc.). In this case, the API will return a response with status 400:

>> response
<Response [400]>
>> response.text
{"statusCode":400,"errorMessage":"Bad Request","errors": ...}
>> response.status_code
400

I thought I could capture this with response.raise_for_status(), but no Exception is raised, and the returned value is None:

>> response.raise_for_status()
None

Why is this? I thought the raise_for_status function was supposed to raise an Exception based on the response's status_code

4
  • raise_for_status() on a response from the requests module will raise an HTTPError exception if the HTTP status code is 400. I can only imagine that this peculiarity is related to OAuth2Session Commented Nov 26, 2021 at 10:19
  • this may help Commented Nov 26, 2021 at 10:25
  • @DarkKnight Yes! Setting session.register_compliance_hook("access_token_response", "raise_on_error") indeed gives me a HTTPError: 400 Client Error: Bad Request, though I think I want it to hook on protected_request instead (I'll dig into this more). Any idea if it's possible to customize the Exception? I'd like to add the error message from the response into the Exception Commented Nov 26, 2021 at 10:48
  • @DarkKnight Nevermind, figured it out already :). Could you post your comment as answer, so I can mark it as the correct answer? Commented Nov 26, 2021 at 11:35

1 Answer 1

1

raise_for_status() on a response from the requests module will raise an HTTPError exception if the HTTP status code is 400. This is a peculiarity of OAuth2Session which you can read about here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.