The Response
object in the requests
library in Python is the encapsulation of the HTTP response received after making a request to a URL. This object contains all the information returned by the server, such as the content of the response, the HTTP status code, headers, and more.
Here's how you can use the Response
object:
- Make a Request: First, you need to make a request to a URL using one of the
requests
methods likeget
,post
,put
,delete
, etc.
import requests
url = "http://example.com"
response = requests.get(url)
- HTTP Status Codes: You can check the status of the response, which indicates whether the request was successful or not.
status_code = response.status_code
print(f"Status Code: {status_code}")
- Response Content: You can access the body of the response in a few different formats:
.text
gives you the content as a Unicode string..content
gives you the raw bytes of the response payload..json()
interprets the response text as JSON and returns the corresponding Python data structure (dict or list), but only if the responseContent-Type
isapplication/json
.
# As a Unicode string
text_content = response.text
print(text_content)
# As raw bytes
byte_content = response.content
print(byte_content)
# As a JSON (if the response is in JSON format)
json_content = response.json()
print(json_content)
- Headers: You can also access the response headers, which can give you metadata about the response, such as content type, server information, etc.
headers = response.headers
print(headers)
- Cookies: If there are any cookies set by the server, you can retrieve them from the response:
cookies = response.cookies
print(cookies)
- History: If the request was redirected, the
Response
object contains the history of theResponse
objects of the previous requests.
history = response.history
print(history)
- URL: You can confirm the final URL of the response, especially if redirection occurred.
final_url = response.url
print(final_url)
- Raise for Status: It's good practice to check if the request was successful and raise an exception if it wasn't:
response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
Remember to install the requests
library if you haven't already:
pip install requests
A complete example of using the Response
object might look like this:
import requests
try:
response = requests.get("http://example.com")
response.raise_for_status() # Raises an HTTPError if the HTTP request returned an unsuccessful status code
print(f"Status Code: {response.status_code}")
print("Headers:", response.headers)
print("Content:", response.text)
if 'json' in response.headers.get('Content-Type'):
print("JSON:", response.json())
except requests.exceptions.HTTPError as errh:
print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"An Error Occurred: {err}")
In this example, we not only use the Response
object to access various parts of the response but also handle potential exceptions that can occur during the request.