Python’s requests
library is a popular and powerful tool for making HTTP requests in a convenient and efficient manner. One of the important aspects of handling HTTP requests is to understand and interpret the status codes returned by the server.
In this blog post, we will explore how to check the status code of a request using the requests
library in Python.
Making a Request
Before checking the status code, let’s briefly cover how to make a request using requests
. First, you need to install the library by running pip install requests
in your terminal. Once installed, you can import the requests
module in your Python script:
import requests
To make a GET request to a URL, you can use the get()
method:
response = requests.get('https://www.example.com')
Checking the Status Code
To check the status code of the response, you can access the status_code
attribute of the response
object:
print(response.status_code)
The status code represents the response from the server, indicating the success or failure of the request. It is a three-digit number, where the first digit represents the response class:
2xx
: Success (e.g. 200 OK)3xx
: Redirection (e.g. 301 Moved Permanently)4xx
: Client Errors (e.g. 404 Not Found)5xx
: Server Errors (e.g. 500 Internal Server Error)
Handling Different Status Codes
Based on the status code, you can implement different actions or error handling logic. Here’s an example of checking for a successful response:
if response.status_code == 200:
print('Request was successful')
You can also use the response.ok
attribute, which returns True
if the status code is less than 400 (i.e., if the request was successful):
if response.ok:
print('Request was successful')
For other status codes, you can handle them accordingly. For example, if the status code indicates a client error (4xx), you can raise an exception or display an appropriate error message to the user.
Conclusion
In this blog post, we explored how to check the status code of a request using the requests
library in Python. Understanding and handling different status codes is essential for effectively working with HTTP requests and building robust applications.
By checking the status code, you can determine the success or failure of the request and take appropriate action based on the response from the server.
Remember to always handle different status codes appropriately, providing meaningful feedback to the user and handling errors gracefully in your application.