requests python get response body

How to Get Response Body from a Python Request

If you need to get the response body from a Python request, you can do so using the requests library. This library allows you to send HTTP/1.1 requests using Python.

Using requests.get() Method

The simplest way to get the response body from a Python request is to use the requests.get() method. This method sends a GET request to the specified URL and returns the response object.


import requests

response = requests.get('https://www.example.com')
print(response.content)

The above code sends a GET request to the example.com URL and prints the response content to the console. The content attribute of the response object contains the response body.

Using Response.text

You can also use the text attribute of the response object to get the response body as a string.


import requests

response = requests.get('https://www.example.com')
print(response.text)

The above code sends a GET request to the example.com URL and prints the response body as a string.

Using Response.json()

If the response body is in JSON format, you can use the json() method of the response object to convert it to a Python dictionary.


import requests

response = requests.get('https://api.example.com/data.json')
data = response.json()
print(data)

The above code sends a GET request to the data.json endpoint of the example.com API and prints the response body as a Python dictionary.

Using Response.content

If you need to get the response body as bytes, you can use the content attribute of the response object.


import requests

response = requests.get('https://www.example.com')
print(response.content)

The above code sends a GET request to the example.com URL and prints the response body as bytes.

Conclusion

Getting the response body from a Python request is easy using the requests library. You can use the content, text, or json() attributes of the response object depending on your needs.