Python Requests Error Response Body
When working with the Python Requests library, it is important to understand how to handle error responses from API calls. An error response usually includes a response body that contains information about the error.
Using the status_code Attribute
The easiest way to check if a request was successful or not is by checking the status code of the response. The status code is a three-digit number that indicates the HTTP status of the response.
Here is an example:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/999')
if response.status_code == 404:
print('Page not found')
In this example, we are trying to access a non-existent user on the JSONPlaceholder API. Since the API returns a 404 Not Found status code, our script will print 'Page not found'.
Accessing the Response Body
If you need to access the response body of an error response, you can use the text attribute of the response object. The text attribute returns the response body as a string.
Here is an example:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/999')
if response.status_code == 404:
print(response.text)
In this example, we are accessing the same non-existent user as before. Since the API returns a 404 Not Found status code, our script will print the response body, which includes an error message.
Using the JSON Response
Many APIs return error messages in JSON format. In this case, you can use the json attribute of the response object to parse the response body into a Python dictionary.
Here is an example:
import requests
response = requests.get('https://api.github.com/users/invalid-url')
if response.status_code == 404:
data = response.json()
print(data['message'])
In this example, we are accessing an invalid URL on the GitHub API. Since the API returns a 404 Not Found status code and a JSON-formatted response body, our script will parse the response body and print the error message.