API Navigator Logo

Python Requests POST JSON Example

Author: Newtum

This example demonstrates how to send a POST request with a JSON payload using the popular Python Requests library. We will cover the basics of JSON, HTTP POST, and how to construct and send the request in Python.

What is the Python Requests library?

The Python Requests library is the de facto standard for making HTTP requests in Python. It abstracts the complexities of making requests behind a simple API, so you can focus on interacting with services and consuming data in your application.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of JavaScript, but is considered a language-independent data format.

JSON Example

A simple JSON object representing a user.

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false
}

JSON Array Example

A JSON array of strings.

[
  "apple",
  "banana",
  "cherry"
]

Complex JSON Example

A more complex JSON object with nested objects and arrays.

{
  "id": "001",
  "user": {
    "name": "Jane Smith",
    "email": "jane@example.com"
  },
  "roles": ["admin", "editor"]
}

What is HTTP POST?

The HTTP POST method is used to send data to a server to create or update a resource. The data sent to the server is stored in the request body of the HTTP request.

HTTP POST Request Example

This is a raw HTTP POST request. The `Content-Type` header is crucial for the server to understand the format of the body.

POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 38

{
  "name": "New User",
  "email": "new@example.com"
}

How to use the Python Requests library?

First, you need to install it. If you haven't already, you can install it using pip.

pip install requests

How to make a POST request with Python?

The `requests.post()` method allows you to send a POST request. The `json` parameter is a convenient way to automatically encode a Python dictionary as a JSON string and set the `Content-Type` header to `application/json`.

import requests

url = 'https://jsonplaceholder.typicode.com/posts'
my_data = {'key': 'value'}

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

print(response.status_code)
print(response.json())

How to send custom HTTP headers with a POST request?

You can pass a dictionary of headers to the `headers` parameter. This is useful for including things like authorization tokens.

import requests

url = 'https://jsonplaceholder.typicode.com/posts'
my_data = {'title': 'foo', 'body': 'bar', 'userId': 1}
headers = {'Authorization': 'Bearer YOUR_TOKEN_HERE', 'X-Custom-Header': 'MyValue'}

response = requests.post(url, json=my_data, headers=headers)

print(response.status_code)
print(response.json())

Python Requests POST JSON Example

Here is a complete example of posting a JSON object to a test API endpoint and printing the response.

import requests
import json

# The API endpoint to which we will send the POST request
url = 'https://jsonplaceholder.typicode.com/posts'

# The data we want to send in JSON format
post_data = {
    'title': 'My Awesome Title',
    'body': 'This is the body of my post.',
    'userId': 101
}

# Sending the POST request with the JSON data
try:
    response = requests.post(url, json=post_data)

    # Check if the request was successful
    response.raise_for_status()

    # Print the status code and the response body (in JSON format)
    print(f"Status Code: {response.status_code}")
    print("Response JSON:")
    print(json.dumps(response.json(), indent=2))

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")