How to Check the Status Code of a Response in Python with requests
Every answer from a web server starts with a status code: 200 for success, 404 when the address doesn't exist, 500 when the server failed. requests doesn't stop your program when the code is an error; it hands you the answer and lets you check response.status_code. This guide asks for three codes and reads them, with real output from Python 3.15.2 and requests 2.34.2.
Syntax
code = response.status_code
if response.status_code != 200:
... # handle the failed request
| Part | What it means |
|---|---|
response.status_code | The status code as a whole number, such as 200 or 404 |
response.ok | True when the code is below 400, False for client and server errors |
The requests quickstart shows r.status_code returning 200, and adds: "Requests also comes with a built-in status code lookup object for easy reference", requests.codes.
Prerequisites
- Python 3 with the requests package in your project, for example with
uv add requests. - An internet connection: httpbin.org's
/status/Nanswers with the status codeN.
Step 1: Ask for Three Status Codes
import requests
for path in ["status/200", "status/404", "status/500"]:
response = requests.get("https://httpbin.org/" + path, timeout=10)
print(path, response.status_code, response.ok)

Step 2: Run It
uv run python status_code.py
status/200 200 True
status/404 404 False
status/500 500 False

All three requests came back without an error, even the 404 and the 500. Only status_code and ok tell them apart.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Using the body without checking the code | A 404 or 500 reaches the code that expects data, and fails there, far from the cause | Check status_code first |
Comparing with the text "200" | status_code is a number, so response.status_code == "200" is always False | Compare with 200 |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| A failed request didn't raise an error | requests raises only for connection problems, not for status codes | Check status_code, or call raise_for_status() |
| You want the words behind the code | status_code is only the number | response.reason gave Not Found for the 404 |
FAQ
What is requests.codes?
Names for the numbers. response.status_code == requests.codes.not_found printed True for the 404, and requests.codes.ok is 200.
Can requests raise the error for me?
Yes: response.raise_for_status() raises requests.HTTPError for any 4xx or 5xx code, and does nothing for a successful one.
Conclusion
response.status_code read 200, 404 and 500 from three requests that all returned without an error, and response.ok was True only for the 200. Checking it is how a program notices a failed request.
Additional Resources
- requests quickstart: Response Status Codes —
status_code,codesandraise_for_status. - requests API: Response —
status_code,okandreason.
