How do you send a POST request with JSON data using Python Requests? | A1Lab@MZeeshanM to PythonEnglish • 5 days ago

How do you send a POST request with JSON data using Python Requests?

message-square
0

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 with 400 Bad Request or 422 Unprocessable Entity.
    • Pass the raw Python dict/list to json=payload, OR if you already hold a pre-serialized JSON string (for example, using custom json.dumps(..., default=str) serializers), pass it to data= 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) with Content-Type: application/x-www-form-urlencoded.
    • requests.post(url, json={"a": 1}) serializes the dictionary as JSON ({"a": 1}) with Content-Type: application/json. If both data= and json= 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 automatic Content-Type: application/json header (unless you explicitly override "Content-Type").
    • For multiple API requests to the same host, reuse a requests.Session() (with requests.Session() as s: s.headers.update(...)) to pool TCP/TLS connections and persist default headers.
  • Handling TypeError: Object of type ... is not JSON serializable: requests’ built-in json= parameter uses standard json.dumps() under the hood, which does not natively serialize datetime, date, Decimal, UUID, or Path objects. Convert those fields beforehand (e.g., .isoformat(), str(...), float(...)) or serialize with a custom default= encoder and pass via data=.
  • Always set timeout= and guard response.json(): Without timeout=(connect_s, read_s), a stalled server can hang your script indefinitely. Also, check response.status_code (or call response.raise_for_status()) before calling response.json(), as 502/504 HTML error pages raise requests.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.