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 = 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.

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: