Python API POST Request Example

This example shows how to send a POST request in Python, send data to an API, and read the response.

The goal is to give you one simple working example you can run right away. If you want a more general guide later, see how to send a POST request in Python or how to make an API request in Python.

Quick example #

import requests

url = "https://httpbin.org/post"
payload = {
    "name": "Alice",
    "age": 25
}

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

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

This sends JSON data to a test API and prints the status code and returned JSON.

Install requests first:

pip install requests

What this example shows #

  • How to send a POST request with Python
  • How to send data as JSON
  • How to read the server response
  • How to check whether the request worked

Before you run the code #

Make sure:

  • Python is installed
  • The requests package is installed with pip
  • You use a safe test endpoint like https://httpbin.org/post

A POST request is often used when you want to send new data to an API. For example, you might create a user, submit a form, or send a message.

Useful commands:

python --version
pip install requests
pip show requests

Basic POST request example #

Here is the same example again with a little more context:

import requests

url = "https://httpbin.org/post"

payload = {
    "name": "Alice",
    "age": 25
}

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

print("Status code:", response.status_code)
print("Response JSON:")
print(response.json())

Example output #

Status code: 200
Response JSON:
{
    "args": {},
    "data": "{\"name\": \"Alice\", \"age\": 25}",
    "files": {},
    "form": {},
    "headers": {
        ...
    },
    "json": {
        "age": 25,
        "name": "Alice"
    },
    "url": "https://httpbin.org/post"
}

The exact output may look a little different, but you should see:

  • A status code such as 200
  • Your sent data inside the returned JSON

How the key lines work #

requests.post() #

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

This sends a POST request to the server.

  • url is the API endpoint
  • json=payload sends your Python dictionary as JSON

If you are new to JSON, see the Python json module overview.

json=payload #

payload = {
    "name": "Alice",
    "age": 25
}

This is a normal Python dictionary.

When you pass it with json=payload, requests converts it to JSON automatically before sending it.

If you need to convert Python data to a JSON string yourself, see json.dumps() explained.

response.status_code #

print(response.status_code)

This shows the HTTP status code from the server.

It helps you check whether the request worked.

response.json() #

print(response.json())

This converts the JSON response into a Python object, usually a dictionary.

If you need to parse a JSON string manually, see json.loads() explained.

Common response checks #

When working with APIs, these status codes are common:

  • 200 or 201 usually means success
  • 400 level codes usually mean your request has a problem
  • 500 level codes usually mean the server has a problem

A simple pattern is:

import requests

url = "https://httpbin.org/post"
payload = {"name": "Alice", "age": 25}

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

print("Status code:", response.status_code)

if response.status_code in (200, 201):
    print("Request worked")
    print(response.json())
else:
    print("Request failed")
    print(response.text)

When debugging, always inspect the response body. It often tells you what went wrong.

You can also read more in how to handle API responses in Python.

Common beginner problems #

Here are some common causes of trouble:

  • requests is not installed
  • The URL or endpoint is wrong
  • You send form data when the API expects JSON
  • You try to parse JSON when the response is not actually JSON
  • You forget to handle network errors
  • The API requires authentication headers or a token

More specifically:

  • ModuleNotFoundError can happen if requests is missing. See how to fix ModuleNotFoundError: No module named x.
  • A 400 response often means the server did not like your data format.
  • Connection errors often mean the URL is wrong or your network is down.
  • JSON parsing can fail if the server returns plain text or HTML instead of JSON.
  • Some APIs require login tokens, API keys, or headers.

One more beginner tip: when reading response data, make sure the key exists before using it. This helps avoid errors like KeyError in Python.

Safer version with error handling #

This version is better for real programs because it handles common problems more safely.

import requests

url = "https://httpbin.org/post"
payload = {
    "name": "Alice",
    "age": 25
}

try:
    response = requests.post(url, json=payload, timeout=10)
    response.raise_for_status()

    print("Status code:", response.status_code)

    content_type = response.headers.get("Content-Type", "")
    if "application/json" in content_type:
        data = response.json()
        print("JSON response:")
        print(data)
    else:
        print("Response is not JSON:")
        print(response.text)

except requests.exceptions.RequestException as e:
    print("Request failed:", e)

What this safer version does #

  • Wraps the request in try-except
  • Catches network and request errors
  • Uses raise_for_status() to catch bad HTTP status codes
  • Checks the response type before calling response.json()
  • Adds a timeout so the program does not wait forever

FAQ #

What is a POST request in Python? #

It is a request that sends data to a server, often to create or submit something.

Should I use data= or json= in requests.post()? #

Use json= when the API expects JSON. Use data= for form-style data.

Why use httpbin.org in the example? #

It is a simple test service that shows back the data you sent.

What does response.status_code mean? #

It is the HTTP status code that tells you whether the request succeeded or failed.

Why does response.json() fail sometimes? #

It fails when the server response is not valid JSON.

See also #

If this copy-paste example works for you, the next step is learning how requests, JSON data, and response debugging fit together in a real API workflow.

Press Esc to close