0
# Status Codes
1
2
Convenient access to HTTP status codes through named constants and lookup functionality. The requests library provides a `codes` object that maps common status code names to their numerical values.
3
4
## Capabilities
5
6
### Status Code Lookup
7
8
The `codes` object provides multiple ways to access status codes by name.
9
10
```python { .api }
11
codes: LookupDict
12
# A lookup dictionary that maps status code names to their numerical values
13
# Supports both attribute and dictionary-style access
14
# Multiple names can map to the same status code
15
# Both upper and lowercase names are supported
16
```
17
18
## Usage Examples
19
20
### Basic Status Code Access
21
22
```python
23
import requests
24
25
# Access status codes by name
26
print(requests.codes.ok) # 200
27
print(requests.codes.not_found) # 404
28
print(requests.codes.internal_server_error) # 500
29
30
# Dictionary-style access
31
print(requests.codes['ok']) # 200
32
print(requests.codes['not_found']) # 404
33
print(requests.codes['server_error']) # 500
34
35
# Case-insensitive access
36
print(requests.codes.OK) # 200
37
print(requests.codes.Ok) # 200
38
print(requests.codes.okay) # 200
39
```
40
41
### Status Code Checking
42
43
```python
44
import requests
45
46
response = requests.get('https://httpbin.org/status/200')
47
48
# Check specific status codes
49
if response.status_code == requests.codes.ok:
50
print("Request successful")
51
52
if response.status_code == requests.codes.not_found:
53
print("Resource not found")
54
55
# Check for success range
56
if 200 <= response.status_code < 300:
57
print("Success")
58
59
# Using response.ok property (shorthand for status < 400)
60
if response.ok:
61
print("Request successful")
62
```
63
64
### Status Code Categories
65
66
```python
67
import requests
68
69
def categorize_status(status_code):
70
"""Categorize HTTP status codes."""
71
if 100 <= status_code < 200:
72
return "Informational"
73
elif 200 <= status_code < 300:
74
return "Success"
75
elif 300 <= status_code < 400:
76
return "Redirection"
77
elif 400 <= status_code < 500:
78
return "Client Error"
79
elif 500 <= status_code < 600:
80
return "Server Error"
81
else:
82
return "Unknown"
83
84
response = requests.get('https://httpbin.org/status/404')
85
category = categorize_status(response.status_code)
86
print(f"Status {response.status_code} is a {category}")
87
```
88
89
### Common Status Code Names
90
91
```python
92
import requests
93
94
# Informational (1xx)
95
codes.continue_ # 100
96
codes.switching_protocols # 101
97
codes.processing # 102
98
99
# Success (2xx)
100
codes.ok # 200
101
codes.okay # 200 (alias)
102
codes.all_ok # 200 (alias)
103
codes.all_good # 200 (alias)
104
codes['\\o/'] # 200 (fun alias)
105
codes['✓'] # 200 (checkmark alias)
106
codes.created # 201
107
codes.accepted # 202
108
codes.no_content # 204
109
110
# Redirection (3xx)
111
codes.multiple_choices # 300
112
codes.moved_permanently # 301
113
codes.moved # 301 (alias)
114
codes.found # 302
115
codes.see_other # 303
116
codes.not_modified # 304
117
codes.temporary_redirect # 307
118
codes.permanent_redirect # 308
119
120
# Client Error (4xx)
121
codes.bad_request # 400
122
codes.unauthorized # 401
123
codes.forbidden # 403
124
codes.not_found # 404
125
codes.method_not_allowed # 405
126
codes.not_acceptable # 406
127
codes.request_timeout # 408
128
codes.conflict # 409
129
codes.gone # 410
130
codes.precondition_failed # 412
131
codes.request_entity_too_large # 413
132
codes.unsupported_media_type # 415
133
codes.too_many_requests # 429
134
135
# Server Error (5xx)
136
codes.internal_server_error # 500
137
codes.server_error # 500 (alias)
138
codes.not_implemented # 501
139
codes.bad_gateway # 502
140
codes.service_unavailable # 503
141
codes.gateway_timeout # 504
142
```
143
144
### Response Status Checking with Codes
145
146
```python
147
import requests
148
149
def handle_response(response):
150
"""Handle response based on status code."""
151
152
if response.status_code == requests.codes.ok:
153
return response.json()
154
155
elif response.status_code == requests.codes.created:
156
print("Resource created successfully")
157
return response.json()
158
159
elif response.status_code == requests.codes.no_content:
160
print("Operation successful, no content returned")
161
return None
162
163
elif response.status_code == requests.codes.not_modified:
164
print("Resource not modified, using cached version")
165
return None
166
167
elif response.status_code == requests.codes.bad_request:
168
print("Bad request - check your parameters")
169
return None
170
171
elif response.status_code == requests.codes.unauthorized:
172
print("Authentication required")
173
return None
174
175
elif response.status_code == requests.codes.forbidden:
176
print("Access forbidden")
177
return None
178
179
elif response.status_code == requests.codes.not_found:
180
print("Resource not found")
181
return None
182
183
elif response.status_code == requests.codes.too_many_requests:
184
print("Rate limit exceeded")
185
return None
186
187
elif response.status_code == requests.codes.internal_server_error:
188
print("Internal server error")
189
return None
190
191
elif response.status_code == requests.codes.service_unavailable:
192
print("Service temporarily unavailable")
193
return None
194
195
else:
196
print(f"Unexpected status code: {response.status_code}")
197
return None
198
199
# Usage
200
response = requests.get('https://api.example.com/data')
201
data = handle_response(response)
202
```
203
204
### Status Code Comparison
205
206
```python
207
import requests
208
209
response = requests.get('https://httpbin.org/status/200')
210
211
# Multiple ways to check for success
212
if response.status_code == 200:
213
print("Success (numeric)")
214
215
if response.status_code == requests.codes.ok:
216
print("Success (using codes)")
217
218
if response.ok:
219
print("Success (using ok property)")
220
221
# Check for specific error conditions
222
if response.status_code in [requests.codes.unauthorized, requests.codes.forbidden]:
223
print("Authentication or authorization error")
224
225
# Check ranges
226
if 400 <= response.status_code < 500:
227
print("Client error")
228
elif 500 <= response.status_code < 600:
229
print("Server error")
230
```
231
232
### Custom Status Code Handling
233
234
```python
235
import requests
236
237
class StatusHandler:
238
"""Custom status code handler."""
239
240
@staticmethod
241
def is_success(status_code):
242
"""Check if status code indicates success."""
243
return 200 <= status_code < 300
244
245
@staticmethod
246
def is_redirect(status_code):
247
"""Check if status code indicates redirect."""
248
return status_code in [
249
requests.codes.moved_permanently,
250
requests.codes.found,
251
requests.codes.see_other,
252
requests.codes.temporary_redirect,
253
requests.codes.permanent_redirect
254
]
255
256
@staticmethod
257
def is_client_error(status_code):
258
"""Check if status code indicates client error."""
259
return 400 <= status_code < 500
260
261
@staticmethod
262
def is_server_error(status_code):
263
"""Check if status code indicates server error."""
264
return 500 <= status_code < 600
265
266
@staticmethod
267
def should_retry(status_code):
268
"""Determine if request should be retried based on status."""
269
retry_codes = [
270
requests.codes.request_timeout,
271
requests.codes.too_many_requests,
272
requests.codes.internal_server_error,
273
requests.codes.bad_gateway,
274
requests.codes.service_unavailable,
275
requests.codes.gateway_timeout
276
]
277
return status_code in retry_codes
278
279
# Usage
280
response = requests.get('https://api.example.com/data')
281
handler = StatusHandler()
282
283
if handler.is_success(response.status_code):
284
data = response.json()
285
elif handler.should_retry(response.status_code):
286
print("Should retry this request")
287
elif handler.is_client_error(response.status_code):
288
print("Client error - check request")
289
else:
290
print("Unexpected status code")
291
```
292
293
### Status Code Logging
294
295
```python
296
import requests
297
import logging
298
299
# Set up logging
300
logging.basicConfig(level=logging.INFO)
301
logger = logging.getLogger(__name__)
302
303
def logged_request(url):
304
"""Make request with detailed status logging."""
305
try:
306
response = requests.get(url)
307
308
# Log status information
309
if response.status_code == requests.codes.ok:
310
logger.info(f"Request successful: {response.status_code}")
311
elif 300 <= response.status_code < 400:
312
logger.info(f"Redirect: {response.status_code} -> {response.headers.get('Location', 'Unknown')}")
313
elif 400 <= response.status_code < 500:
314
logger.warning(f"Client error: {response.status_code} - {response.reason}")
315
elif 500 <= response.status_code < 600:
316
logger.error(f"Server error: {response.status_code} - {response.reason}")
317
else:
318
logger.info(f"Unexpected status: {response.status_code}")
319
320
return response
321
322
except requests.exceptions.RequestException as e:
323
logger.error(f"Request failed: {e}")
324
raise
325
326
# Usage
327
response = logged_request('https://httpbin.org/status/404')
328
```
329
330
## Complete Status Code Reference
331
332
The `codes` object includes mappings for all standard HTTP status codes with multiple name variations:
333
334
### Informational (1xx)
335
- `continue` (100)
336
- `switching_protocols` (101)
337
- `processing` (102)
338
339
### Success (2xx)
340
- `ok`, `okay`, `all_ok`, `all_good`, `\\o/`, `✓` (200)
341
- `created` (201)
342
- `accepted` (202)
343
- `no_content` (204)
344
- `partial_content` (206)
345
346
### Redirection (3xx)
347
- `moved_permanently`, `moved` (301)
348
- `found` (302)
349
- `see_other`, `other` (303)
350
- `not_modified` (304)
351
- `temporary_redirect` (307)
352
- `permanent_redirect` (308)
353
354
### Client Error (4xx)
355
- `bad_request` (400)
356
- `unauthorized` (401)
357
- `forbidden` (403)
358
- `not_found` (404)
359
- `method_not_allowed` (405)
360
- `request_timeout` (408)
361
- `conflict` (409)
362
- `gone` (410)
363
- `too_many_requests` (429)
364
365
### Server Error (5xx)
366
- `internal_server_error`, `server_error` (500)
367
- `not_implemented` (501)
368
- `bad_gateway` (502)
369
- `service_unavailable` (503)
370
- `gateway_timeout` (504)
371
372
Many codes have multiple aliases - both the formal name and common variations are supported.