How to Check the Return Code of a Request in Python?

Estimated read time 1 min read

To check the return code of a request in Python, you can use the requests library. The requests library allows you to send HTTP requests and handle the responses. Here’s an example of how you can check the return code of a request using requests:

import requests

# Send a GET request
response = requests.get("https://api.example.com/endpoint")

# Check the return code
if response.status_code == 200:
    print("Request successful")
else:
    print("Request failed with status code:", response.status_code)

In the code above, we import the requests library. Then, we use the get() function from requests to send a GET request to the specified URL. The response from the request is stored in the response variable.

To check the return code, we access the status_code attribute of the response. In this example, if the status code is 200, which corresponds to a successful request, we print “Request successful”. Otherwise, we print “Request failed with status code:” followed by the actual status code.

You can customize the logic and actions based on different status codes to handle the response accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply