To POST JSON with Python requests, pass a dict to the json parameter: requests.post(url, json=payload, timeout=10). Requests converts the dict to JSON and sets Content-Type: application/json for you; using data= with a dict sends a form instead, which is the most common reason an API rejects the request.
import requests
payload = {"name": "Widget", "price": 9.99, "tags": ["a", "b"]}
r = requests.post("http://127.0.0.1:8765/items", json=payload, timeout=10)
r.raise_for_status()
print(r.json())
Every example on this page was run with Python 3.12 and requests 2.32.3 against a small echo server on 127.0.0.1 that reports back the Content-Type it received and whether the body parsed as JSON. The output shown is the real output.
json= vs data=: what actually gets sent
The same dict produces three different requests depending on how you pass it:
r = requests.post(url, json=payload, timeout=10)
print(r.request.headers["Content-Type"], r.request.body)
r = requests.post(url, data=payload, timeout=10)
print(r.request.headers["Content-Type"], r.request.body)
r = requests.post(url, data=json.dumps(payload), timeout=10)
print(r.request.headers.get("Content-Type"))
Output:
application/json b'{"name": "Widget", "price": 9.99, "tags": ["a", "b"]}'
application/x-www-form-urlencoded name=Widget&price=9.99&tags=a&tags=b
None
| Call | Body | Content-Type sent | Server sees JSON? |
|---|---|---|---|
json=payload | JSON text | application/json | Yes |
data=payload (a dict) | Form fields | application/x-www-form-urlencoded | No: our server returned 400 "body is not JSON" |
data=json.dumps(payload) | JSON text | None | Only if the server ignores the header |
The third form is what older tutorials show. The requests documentation warns that it "will NOT add the Content-Type header". Our lenient test server parsed it anyway, but a server that checks the header can treat the body as plain text or reject it with 415 Unsupported Media Type. If you really need to send a pre-encoded string, set the header yourself:
r = requests.post(
url,
data=json.dumps(payload),
headers={"Content-Type": "application/json"},
timeout=10,
)
Don't pass both: the docs state that json "is ignored if either data or files is passed".
Read the JSON response, and check the status first
r.json() parses the reply body. It does not tell you the request succeeded. The requests docs point out that servers often return a JSON error object with a 4xx or 5xx status, and r.json() will happily decode it. Check the status before you trust the data:
r = requests.post("http://127.0.0.1:8765/fail", json=payload, timeout=10)
print(r.status_code, r.ok)
r.raise_for_status()
Output:
422 False
requests.exceptions.HTTPError: 422 Client Error: Unprocessable Entity for url: http://127.0.0.1:8765/fail
raise_for_status() raises HTTPError for any 4xx or 5xx status and does nothing otherwise. Before raising, it is often worth logging r.text, because the server's error body usually says which field it rejected. For what each status means, see HTTP status codes explained.
If the reply is not JSON at all (an HTML error page, or an empty 204), r.json() raises requests.exceptions.JSONDecodeError. Posting to Python's built-in http.server, which answers POST with a 501 HTML page, gives:
501 text/html;charset=utf-8
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
"line 1 column 1 (char 0)" means the parser found no JSON at the very first character. Check r.headers["Content-Type"] and r.text to see what came back instead.
A complete, production-shaped POST
import os
import requests
def create_item(payload: dict) -> dict:
r = requests.post(
"https://api.example.com/items",
json=payload,
headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
timeout=10,
)
if not r.ok:
raise RuntimeError(f"POST /items failed: {r.status_code} {r.text[:200]}")
return r.json()
Three details matter here:
timeout=10. Requests has no default timeout. The docs say that without one a request can "hang indefinitely", and that nearly all production code should set it. The value is the seconds to wait for the server to send any bytes, not a cap on the whole download.- The token comes from the environment, not from the source file.
- The error includes the start of the response body, so the log says why the server refused, not only that it did.
For many requests to the same API, a requests.Session reuses the connection and lets you set shared headers once:
s = requests.Session()
s.headers.update({"Authorization": f"Bearer {os.environ['API_TOKEN']}"})
r = s.post(url, json=payload, timeout=10)
Errors you will hit
TypeError: Object of type datetime is not JSON serializable
json= can only encode types the standard json module understands: dict, list, str, int, float, bool and None. A datetime, Decimal, UUID or set raises this before anything is sent:
requests.post(url, json={"when": datetime.datetime(2026, 11, 8)}, timeout=10)
# TypeError: Object of type datetime is not JSON serializable
Convert the value first, for example {"when": dt.isoformat()}, or encode it yourself with json.dumps(payload, default=str) and send that with data= plus the header. The default function is called for any object the encoder can't handle.
InvalidJSONError: Out of range float values are not JSON compliant: nan
JSON has no NaN or Infinity. Python's json.dumps writes them anyway by default, but requests refuses:
requests.exceptions.InvalidJSONError: Out of range float values are not JSON compliant: nan
Replace NaN with None (sent as null) before posting. This one often comes from pandas data.
ConnectionError: Max retries exceeded ... actively refused it
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8799): Max retries exceeded with url: /items (Caused by NewConnectionError('...: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
Nothing is listening on that host and port. "Max retries exceeded" is misleading: requests' default retry count is 0 (requests.adapters.DEFAULT_RETRIES), and the wording comes from the underlying urllib3 library. Check the URL and port, and that the server is running.
Non-ASCII text arrives as é
Posting {"a": "é"} sends the body {"a": "é"}. That is valid JSON: the json module escapes non-ASCII characters by default (ensure_ascii=True), and any JSON parser turns é back into é. You only see the escape if you look at the raw bytes. RFC 8259 requires UTF-8 for JSON exchanged between systems, which escaped ASCII output satisfies.
Test against a local server, not a production API
To see exactly what your code sends, run a throwaway echo server. This one uses only the standard library, listens on 127.0.0.1 only, and returns the received Content-Type and parsed body:
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class Echo(BaseHTTPRequestHandler):
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
try:
status, reply = 200, {"received": json.loads(raw)}
except ValueError:
status, reply = 400, {"error": "body is not JSON", "raw": raw.decode("utf-8", "replace")}
reply["content_type"] = self.headers.get("Content-Type")
body = json.dumps(reply).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
HTTPServer(("127.0.0.1", 8765), Echo).serve_forever()
Run it in one terminal, run your client in another, and stop the server with Ctrl+C. If you only need to inspect the outgoing request without a server, build it and print it: p = requests.Request("POST", url, json=payload).prepare(), then look at p.headers and p.body. If you are parsing JSON from files rather than responses, json.load vs json.loads covers the other side.
Frequently asked questions
- What is the difference between json= and data= in requests.post?
- json= serialises a Python dict or list to JSON and sets the Content-Type header to application/json. data= with a dict sends the fields as a form (application/x-www-form-urlencoded). data= with a string sends the string as-is with no Content-Type header, so you must add the header yourself.
- Do I need to set Content-Type: application/json myself?
- Not when you use json=. Requests adds Content-Type: application/json automatically. If you pass your own Content-Type header, such as application/vnd.api+json, yours is kept. You only need to set it by hand when you send a pre-encoded string with data=.
- How do I send a JSON array instead of an object?
- Pass a list to json=, for example requests.post(url, json=[1, 2, 3], timeout=10). The body is sent as [1, 2, 3] with Content-Type: application/json, the same as for a dict.
- How do I send an API key with a JSON POST?
- Add it as a header, for example headers={"Authorization": "Bearer " + token}, and read the token from an environment variable rather than writing it in the code. If you make many requests, set the header once on a requests.Session and reuse the session.