Python Requests Status Code
If you are working with Python and trying to make HTTP requests, you will likely come across the status code. The status code is a three-digit number that is returned by the server in response to a request. It indicates the status of the request, whether it was successful or not, and what action you should take next.
Using Python Requests
Python Requests is a popular library for making HTTP requests in Python. It provides an easy-to-use interface for sending HTTP requests and handling responses. When you make a request using Requests, the library will automatically handle the status code returned by the server.
import requests
response = requests.get('https://www.example.com')
print(response.status_code)
In the above example, we are making a GET request to the example.com website using Requests. The status code returned by the server is stored in the status_code
attribute of the Response object.
Interpreting Status Codes
HTTP status codes are grouped into five categories, based on their first digit:
- 1xx (Informational): The request was received, and the server is continuing to process it.
- 2xx (Successful): The request was successful, and the server has delivered the requested content.
- 3xx (Redirection): The request needs further action to be completed, such as following a redirect.
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled by the server.
- 5xx (Server Error): The server failed to fulfill a valid request.
For example, a status code of 200
means the request was successful, while a code of 404
means the requested resource was not found.
Handling Errors with Requests
If the server returns a status code that indicates an error, such as 404
or 500
, Requests will raise an exception. You can catch this exception and handle it appropriately.
import requests
try:
response = requests.get('https://www.example.com/doesnotexist')
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
In the above example, we are trying to make a GET request to a non-existent page on the example.com website. Requests will raise an HTTPError exception with a message indicating the problem.