Python Requests Response Body
Python Requests is a popular library used for making HTTP requests in Python. It allows us to send HTTP/1.1 requests and provides easy access to the response body and headers. In this post, we will discuss how to access the response body in Python Requests.
Accessing Response Body
To access the response body, we need to use the .text
attribute of the response object.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.text)
The above code will print the response body of the HTTP request. It is important to note that the response body is returned as a string.
Accessing Response Content
The response body can also be accessed using the .content
attribute of the response object. This returns the response content in bytes, which can be useful for binary data such as images.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.content)
Response Encoding
By default, Requests will try to guess the encoding of the response based on the HTTP headers. If the encoding cannot be determined, it will fall back to ISO-8859-1. We can access the encoding of the response using the .encoding
attribute of the response object.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.encoding)
Response Headers
In addition to the response body, we can also access the response headers using the .headers
attribute of the response object.
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
print(response.headers)
The above code will print a dictionary containing the response headers.
Conclusion
In this post, we discussed how to access the response body in Python Requests. We also covered how to access the response content, encoding, and headers. Knowing how to access these attributes can be useful when working with HTTP requests in Python.