Handling Responses in Requests
When you make HTTP requests with the Requests library, the server sends back a response. Understanding how to handle these responses is crucial for effective API interactions.
Accessing Response Content
The content of an HTTP response can be accessed in multiple formats depending on your requirements.
Accessing Text Content
Use the .text
attribute to retrieve the response as a string.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Response Text:", response.text)
Accessing JSON Content
If the server returns JSON data, use the .json()
method to parse it into a Python dictionary.
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Response JSON:", response.json())
Accessing Binary Content
Use the .content
attribute to retrieve the raw binary content of the response.
response = requests.get("https://via.placeholder.com/150")
with open("image.png", "wb") as f:
f.write(response.content)
Status Codes and Handling Errors
Checking the Status Code
Every HTTP response has a status code that indicates the result of the request.
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Status Code:", response.status_code)
Common Status Codes
Code | Meaning |
---|---|
200 | OK |
201 | Created |
400 | Bad Request |
401 | Unauthorized |
404 | Not Found |
500 | Internal Server Error |
Raising Exceptions for Errors
Use the .raise_for_status()
method to raise an exception for HTTP errors.
try:
response = requests.get("https://jsonplaceholder.typicode.com/invalid")
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print("HTTP Error:", e)
HTTP Headers in Responses
HTTP headers provide additional information about the response, such as content type, server details, and caching policies.
Accessing Headers
The .headers
attribute returns a dictionary of response headers.
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print("Headers:", response.headers)
Example: Accessing Specific Header
print("Content-Type:", response.headers["Content-Type"])
Try It Yourself
Problem 1: Fetch JSON Data
Retrieve and print the title of the post from https://jsonplaceholder.typicode.com/posts/1
.
Show Solution
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()
print("Title:", data["title"])
Problem 2: Save an Image from a URL
Download an image from https://via.placeholder.com/150
and save it as placeholder.png
.
Show Solution
import requests
response = requests.get("https://via.placeholder.com/150")
with open("placeholder.png", "wb") as f:
f.write(response.content)
By understanding how to handle responses, you can effectively manage data returned from APIs, detect errors, and work with server headers. Start practicing these concepts to enhance your skills!