Check an exact response status
After any HTTP request, inspect whether the server returned the expected status.
Requests · Const
Response.status_code is the integer HTTP status returned by a server, such as 200 or 404. Use it for exact status checks, optionally comparing it with a named value from requests.codes.
A response's status_code is the integer HTTP status returned by the server, such as 200 or 404. Read it directly for exact comparisons, or compare it with a named value from requests.codes when that improves readability.
Response.status_codeint
import requests
response = requests.get("https://httpbin.org/status/204")
print(response.status_code)
if response.status_code == requests.codes.no_content:
print("No content")Fetches a response, reads its integer HTTP status, and compares it with the named Requests status-code constant.
After any HTTP request, inspect whether the server returned the expected status.
Use a readable named status instead of embedding a numeric literal.
Branch application behavior for success, redirection, client-error, or server-error responses.
Read the integer directly from the Response object: response.status_code. The documentation describes it as the returned HTTP status code and gives values such as 404 and 200.
Follow-up: How can a named status value improve readability? Compare the integer with a corresponding requests.codes attribute, such as requests.codes.ok.
Use an exact comparison, for example response.status_code == 200. Requests also provides named constants through requests.codes, so requests.codes.ok can represent 200.
Follow-up: What should you use when any client or server error should fail? Call response.raise_for_status(), which raises HTTPError when an error occurred.
status_code is an integer property on the Response object; it does not itself raise an exception for an error response. Error handling is separate and can be performed with raise_for_status().
Follow-up: Why might status_code be preferable to ok? It distinguishes specific outcomes, while ok is true for every status below 400.
Response.okResponse.raise_for_status()requests.codesResponse