Pass a Python dictionary (or list) directly to the json= parameter of requests.post(url, json=payload)—which automatically serializes the data to a JSON string, encodes it as UTF-8, and sets the Content-Type: application/json request header for you.
Basic Example
import requests
url = "[https://httpbin.org/post](https://httpbin.org/post)"
payload = {
"user_id": 42,
"username": "alice",
"active": True,
"roles": ["admin", "editor"],
}
# Recommended: Pass Python dict/list directly to json=
response = requests.post(url, json=payload, timeout=10)
# Raise requests.HTTPError for 4xx/5xx status codes
response.raise_for_status()
# Parse the JSON response body back into a Python dict
data = response.json()
print("Status:", response.status_code) # Output: 200
print("Sent Content-Type:", data["headers"]["Content-Type"]) # Output: application/json
print("Echoed JSON:", data["json"])
Key Details & Edge Cases
- Do NOT pass an already-serialized JSON string to
json=:requests.post(url, json=json.dumps(payload))double-encodes your payload into a JSON string literal ("{\"user_id\": 42}") instead of a JSON object, which causes most REST APIs to reject it with400 Bad Requestor422 Unprocessable Entity.- Pass the raw Python
dict/listtojson=payload, OR if you already hold a pre-serialized JSON string (for example, using customjson.dumps(..., default=str)serializers), pass it todata=and set the header manually:import json from datetime import datetime import requests raw_json = json.dumps({"timestamp": datetime.now()}, default=str) response = requests.post( url, data=raw_json.encode("utf-8"), headers={"Content-Type": "application/json"}, timeout=10, )
- Sending
json=vs.data=(Form-Encoded):requests.post(url, data={"a": 1})encodes the dictionary as URL-encoded form data (a=1) withContent-Type: application/x-www-form-urlencoded.requests.post(url, json={"a": 1})serializes the dictionary as JSON ({"a": 1}) withContent-Type: application/json. If bothdata=andjson=are provided,json=is ignored.
- Custom headers, authentication, and
requests.Session():- Any extra headers you pass in
headers={"Authorization": "Bearer <token>"}merge cleanly with the automaticContent-Type: application/jsonheader (unless you explicitly override"Content-Type"). - For multiple API requests to the same host, reuse a
requests.Session()(with requests.Sessio() as s: s.headers.up(...)) to pool TCP/TLS connections and persist default headers.
- Any extra headers you pass in
- Handling
TypeError: Object of type ... is not JSON serializable:requests’ built-injson=parameter uses standardjson.dumps()under the hood, which does not natively serializedatetime,date,Decimal,UUID, orPathobjects. Convert those fields beforehand (e.g.,.isoformat(),str(...),float(...)) or serialize with a customdefault=encoder and pass viadata=. - Always set
timeout=and guardresponse.json(): Withouttimeout=(connect_s, read_s), a stalled server can hang your script indefinitely. Also, checkresponse.status_code(or callresponse.raise_for_status()) before callingresponse.json(), as502/504HTML error pages raiserequests.exceptions.JSONDecodeError.
Comparison of requests.post() Payload Parameters
| Parameter | Expected Input Type | Serialization Behavior | Automatic Content-Type Header |
Best Used When |
|---|---|---|---|---|
json=payload |
dict, list, or JSON-compatible primitive |
Calls json.dumps(payload) automatically |
application/json |
Sending standard JSON API payloads from Python dicts/lists. |
data=raw_str |
Pre-serialized str or UTF-8 bytes |
Sent verbatim as raw body | text/plain (must set application/json manually) |
Sending custom-serialized JSON (e.g., datetime encoders or canonical HMAC-signed bodies). |
data=form_dict |
dict or list of (key, val) tuples |
URL-encodes as key1=val1&key2=val2 |
application/x-www-form-urlencoded |
Submitting standard HTML forms or OAuth2 token endpoints. |
files=files_dict |
dict mapping field names to file objects |
Multipart boundary encoding | multipart/form-data; boundary=... |
Uploading binary files alongside form fields. |
You must log in or register to comment.
