Junior — Middle
Share your experience in using and handling HTTP status codes in your projects.
sobes.tech AI
Answer from AI
In Python projects, I often used HTTP status codes to handle responses from APIs and web services. Key points:
- Checking the response code to determine success (e.g., 200 OK) or errors (4xx, 5xx).
- Handling redirects (3xx) if necessary.
- Logging and informing the user about error reasons, such as 401 Unauthorized or 404 Not Found.
- In REST APIs, I often return appropriate codes so that clients can respond correctly.
Example of handling a response with requests:
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
# process data
elif response.status_code == 404:
print('Resource not found')
else:
print(f'Server error: {response.status_code}')
This approach helps make applications more robust and informative.