Sending and Receiving JSON Data with Python Requests

Feb 3, 2024 ยท 2 min read

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 json parameter. Requests will serialize the dict to JSON and add the correct Content-Type header for you:

import requests

data = {
    'name': 'John Doe',
    'age': 30

response ='', 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('') 
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 = ''
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.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!