python requests post response status code

Python Requests Post Response Status Code

If you're working with APIs, web scraping, or any kind of HTTP requests in Python, you'll likely be using the requests library. One common task when making HTTP requests is to check the response status code to see if the request was successful or not.

Using the requests.post() Method

The requests.post() method is used to send a POST request to a specified URL. This method returns a response object which contains various information about the request, including the status code. Here's an example:


import requests

url = 'https://example.com/'
data = {'key': 'value'}

response = requests.post(url, data=data)

print(response.status_code)

In this example, we're sending a POST request to https://example.com/ with some data. The response object is stored in the response variable, and we can access the status code using response.status_code.

Handling Errors

The HTTP status code is a 3-digit number that indicates the status of the request. There are many possible status codes, but some common ones are:

  • 200: OK - The request was successful
  • 401: Unauthorized - Authentication failed or user does not have permissions for the requested operation
  • 404: Not Found - The requested resource could not be found
  • 500: Internal Server Error - The server encountered an error while processing the request

It's important to check the status code to make sure the request was successful. If the status code indicates an error, you may want to handle it in some way. Here's an example:


if response.status_code == 200:
    print('Request successful')
elif response.status_code == 401:
    print('Authentication failed')
elif response.status_code == 404:
    print('Resource not found')
else:
    print('Something went wrong')

In this example, we're checking the status code and printing a message based on the outcome. You can customize this logic to suit your needs.

Conclusion

Checking the response status code is an important part of working with HTTP requests in Python. Use the requests.post() method to send a POST request and retrieve the response object, then access the status code using response.status_code. Make sure to handle any errors appropriately.