API Navigator Logo

Working with JSON in Python Requests

Author: Newtum

This guide focuses on how to send and receive JSON data using the Python Requests library. JSON is the most common format for data exchange in modern APIs.

Sending JSON Data in a POST Request

Requests has a convenient `json` parameter that automatically handles serializing your Python dictionary to a JSON string and setting the `Content-Type` header to `application/json`.

import requests

url = 'https://api.restful-api.dev/objects'
payload = {
   "name": "Apple MacBook Pro 16",
   "data": {
      "year": 2019,
      "price": 1849.99,
      "CPU model": "Intel Core i9",
      "Hard disk size": "1 TB"
   }
}

response = requests.post(url, json=payload)

print('Status Code:', response.status_code)
print('Response JSON:', response.json())

Decoding a JSON Response

If the API returns a JSON response, you can use the `.json()` method on the response object. This will parse the JSON response and return a Python dictionary or list.

import requests

response = requests.get('https://jsonplaceholder.typicode.com/todos/1')

if response.status_code == 200:
    # .json() decodes the response body
    data = response.json()
    print('Type of data:', type(data))
    print('Title:', data['title'])
else:
    print('Failed to retrieve data. Status code:', response.status_code)