The Python Requests library makes it easy to send HTTP requests and receive responses. When working with APIs or web services, data is often exchanged in JSON format. The Requests module has built-in support for encoding and decoding JSON seamlessly.
Sending JSON Data
To send JSON data in a POST or PUT request, simply pass a Python dict to the
import requests
data = {
'name': 'John Doe',
'age': 30
}
response = requests.post('https://api.example.com/users', json=data)
No need to encode to JSON yourself! This makes working with web APIs that accept JSON very straightforward.
Handling JSON Responses
Many modern web APIs return JSON formatted responses. Requests will automatically decode the JSON response so you can access it as a Python dict or list:
response = requests.get('https://api.example.com/users/123')
user = response.json()
print(user['name']) # John Doe
This saves you the step of manually decoding the JSON yourself.
Practical Example: GitHub API
Here's a practical example using the GitHub API to retrieve a user's profile information:
import requests
url = 'https://api.github.com/users/octocat'
response = requests.get(url)
octocat = response.json()
print(octocat['name']) # The Octocat
The GitHub API returns JSON for all responses, which Requests nicely decodes for us.
Handling JSON data is a breeze with Requests. The automatic encoding and decoding means you can focus on working with the data rather than fiddling with serialization.