Every time your program makes an API request, the server responds with more than just data — it responds with a status code. This three-digit number says: “everything’s fine,” “that doesn’t exist,” “access denied,” or “I’m broken.”
Status Code Groups
Status codes are grouped by their leading digit:
| Range | Meaning |
|---|---|
| 1xx | Informational (rarely seen) |
| 2xx | Success |
| 3xx | Redirection |
| 4xx | Client-side error (your mistake) |
| 5xx | Server-side error |
The Most Important Codes
200 OK
Everything is fine. Request succeeded, data received.
response = requests.get("https://api.chucknorris.io/jokes/random")
print(response.status_code) # 200
201 Created
Resource successfully created. You get this in response to a POST request (creating a repository, publishing an article).
204 No Content
Success, but the response body is empty. Typical after deleting a record.
400 Bad Request
The server couldn’t understand your request. Usually means a malformed or invalid parameter.
{"cod": "400", "message": "bad request"}
401 Unauthorized
Not authenticated. API key is missing or invalid.
{"cod": 401, "message": "Invalid API key"}
403 Forbidden
Authenticated, but not authorized. For example, trying to modify someone else’s repository.
404 Not Found
Not found. The URL is wrong or the requested resource doesn’t exist.
{"cod": "404", "message": "city not found"}
422 Unprocessable Entity
Request syntax is correct but the data is invalid (e.g., a date in the wrong format).
429 Too Many Requests
Rate limit exceeded. Wait and try again.
500 Internal Server Error
The server crashed. This is not your fault — the problem is on the service’s end.
502 Bad Gateway / 503 Service Unavailable
Server temporarily unavailable. Try again later.
Handling Status Codes in Python
Option 1 — manual check
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
elif response.status_code == 404:
print("Not found")
elif response.status_code == 401:
print("Invalid key")
Option 2 — raise_for_status()
raise_for_status() automatically raises an HTTPError if the status code is >= 400:
try:
response = requests.get(url, params=params)
response.raise_for_status() # ← raises on 4xx or 5xx
data = response.json()
except requests.exceptions.HTTPError as e:
print(f"Error: {e.response.status_code}")
Option 2 is more concise and idiomatic — use it in production code.
The 4xx vs 5xx Rule
- 4xx — you did something wrong. Fix your request.
- 5xx — the server did something wrong. Wait, or contact support.
Practice: Viewing Status Codes in the Browser
- Open DevTools (F12) → Network tab
- Navigate to any website
- Click on any request
- Find Status Code in the Headers section
You’ll see 200 for successfully loaded resources and 304 (Not Modified, served from cache) for resources that haven’t changed.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!