Guard response handling
Validate an HTTP response before parsing or processing its body.
Requests · Function
Response.raise_for_status() raises HTTPError for an unsuccessful HTTP response and otherwise returns None. Use it after a request to enforce response-status validation before handling the result.
Call this method on a Response after the request completes. It raises requests.exceptions.HTTPError when the response has an unsuccessful status code; otherwise, it returns None, so it can be used as a concise validation step before processing the response.
raise_for_status() → NoneNone when no HTTP error is raised; otherwise the method raises HTTPError.
import requests
response = requests.get("https://httpbin.org/status/404")
try:
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)The call raises HTTPError for this 404 response, allowing the failure to be handled explicitly.
Validate an HTTP response before parsing or processing its body.
Convert 4XX and 5XX server responses into an exception path.
Keep request code concise when successful responses need no explicit status branch.
It is a Response method with the signature raise_for_status() → None. It raises HTTPError when an unsuccessful status code occurred and returns None when no such error occurred.
Follow-up: How would you distinguish HTTP failures from transport failures? Catch HTTPError for an unsuccessful response; connection problems are handled separately by Requests exceptions such as ConnectionError.
The method validates the completed response rather than checking only for 200 OK. A successful call returns None, while an unsuccessful response causes HTTPError to be raised.
Follow-up: Why might checking only status code 200 be too strict? Other successful HTTP responses can use different status codes, so exact equality with 200 is not the method's criterion.
It is useful immediately after a request and before consuming the response as successful application data. If the server returned an unsuccessful status, execution transfers through HTTPError handling instead.
Follow-up: What should code do after catching HTTPError? It can inspect the exception or response context, log the failure, and apply an application-specific recovery or reporting policy.
ResponseResponse.status_codeResponse.okHTTPErrorrequests.get