How to Post JSON Data With Python Requests
Use Requests’ `json=` parameter to send a Python object as JSON, check the HTTP status, and parse the response safely.

To post JSON with Python Requests, pass a dictionary, list, or other JSON-serializable object to json=. Requests serializes it and uses the JSON request workflow for you. Set a finite timeout, check the HTTP status, then parse the response if it contains JSON:
import requests
url = "https://api.example.com/items"
payload = {"name": "Alice", "active": True}
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
result = response.json()
print(result)
Use data= for form data or a body you have serialized yourself, and files= for multipart uploads. These parameters describe different body formats. In particular, if you pass data or files, Requests ignores json. This guide explains the complete request pattern, how to handle responses and errors, and what to change for common API requirements.
1. Install Requests and make your first JSON request
Install Requests in the Python environment that runs your script:

python -m pip install requests
Then send a JSON object with requests.post(). Replace the example endpoint with the URL documented by the API you are calling. This example raises an exception for unsuccessful HTTP status codes before attempting to read a JSON response.
import requests
url = "https://api.example.com/items"
payload = {
"name": "Alice",
"active": True,
"tags": ["developer", "python"],
}
try:
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
result = response.json()
print("Created item:", result)
except requests.exceptions.Timeout:
print("The API did not respond before the timeout.")
except requests.exceptions.HTTPError as exc:
print("The API returned an unsuccessful HTTP status:", exc)
print("Response body:", response.text)
except requests.exceptions.RequestException as exc:
print("The request failed:", exc)
except requests.exceptions.JSONDecodeError:
print("The response was not valid JSON:", response.text)
The call can raise a connection-level exception before a response exists, so only inspect response in code paths where the request returned one. The example handles HTTP errors separately because those include a response. For a larger application, catch exceptions at the boundary where you can decide whether to retry, report the failure, or return an error to a caller.
Requests’ API describes json as a JSON-serializable Python object sent in the request body. Its Quickstart demonstrates requests.post(url, json=payload) as the direct approach. See the official Requests API reference and Quickstart.
2. Choose the right body parameter
The parameter determines how the request body is constructed. For a JSON API, use json= unless the API specifically documents another format.

| Goal | Requests call | Body behavior |
|---|---|---|
| Send JSON | requests.post(url, json=payload) |
Requests serializes the Python object for the JSON workflow. |
| Submit form fields | requests.post(url, data=form_data) |
A dictionary is encoded as form data. |
| Upload files | requests.post(url, files=files) |
Requests builds a multipart request. |
| Send JSON text you already serialized | requests.post(url, data=json_text) |
You control serialization and must set the appropriate content type yourself. |
Do not supply json alongside data or files expecting Requests to combine them. The Quickstart states that json is ignored if either of those parameters is passed.
JSON versus form-encoded data
A JSON body might look like {"name":"Alice","active":true}. Form data is encoded differently, commonly as fields such as name=Alice&active=true. An API may accept only one of these formats. Follow its endpoint documentation; a server that expects JSON can reject a valid form submission, and the reverse is also true.
# JSON request body
requests.post(url, json={"name": "Alice"}, timeout=10)
# Form-encoded request body
requests.post(url, data={"name": "Alice"}, timeout=10)
For an ordinary HTML form submission, data= is usually the right choice. For an API endpoint that documents a JSON body, use json=.
When to serialize JSON manually
Most callers should not need to serialize manually. If you do, import Python’s json module, create the JSON string, pass it as data=, and set the content type explicitly:
import json
import requests
url = "https://api.example.com/items"
payload = {"name": "Alice", "active": True}
json_text = json.dumps(payload)
response = requests.post(
url,
data=json_text,
headers={"Content-Type": "application/json"},
timeout=10,
)
response.raise_for_status()
The Requests Quickstart warns that passing serialized JSON this way does not add the Content-Type: application/json header automatically. Forgetting the header can cause an API to treat the body as an unsupported or unexpected format. If you have a JSON-serializable object, prefer json=payload; it avoids this easy-to-miss setup step.
3. Build the payload correctly
Python dictionaries, lists, strings, numbers, booleans, and None can be represented in JSON, subject to JSON serialization rules. Python’s values are converted to their JSON equivalents: for example, True becomes true and None becomes null. A list is useful when the endpoint expects an array at the top level rather than an object.
# Object payload
payload = {"user_id": 42, "enabled": True, "nickname": None}
# Array payload
payload = [
{"sku": "A-1", "quantity": 2},
{"sku": "B-3", "quantity": 1},
]
response = requests.post(url, json=payload, timeout=10)
Check the API schema for required keys, value types, nesting, and whether omitted fields differ from fields set to null. A JSON serializer can produce syntactically valid JSON that the API still rejects because a field is missing, has the wrong type, or violates a business rule.
Values such as datetime objects, sets, and custom classes are not directly JSON-serializable by default. Convert them to the representation the API expects first, such as an ISO-formatted string for a documented date field, or a list for a collection. Do not assume the server will infer the conversion.
4. Add authentication, headers, and query parameters
APIs often require credentials or additional headers. Supply headers with a dictionary. Keep secret keys out of source code and logs; load them from an environment variable or a secret manager in real applications.
import os
import requests
url = "https://api.example.com/items"
payload = {"name": "Alice"}
api_token = os.environ["API_TOKEN"]
response = requests.post(
url,
json=payload,
headers={
"Authorization": f"Bearer {api_token}",
"Accept": "application/json",
},
timeout=10,
)
response.raise_for_status()
When using json=, you generally do not need to set Content-Type manually. Set other headers only when the API requires them. The Accept header expresses the response format your client can handle; it does not control how Requests serializes the request body.
Query parameters belong in params=, separate from JSON body fields. Requests URL-encodes them:
response = requests.post(
"https://api.example.com/items",
params={"dry_run": "true", "source": "import"},
json={"name": "Alice"},
timeout=10,
)
Use the API’s documented authentication method. Some services expect a bearer token, others use a custom header, basic authentication, or credentials in a request body. Avoid putting secrets in query strings because URLs are commonly retained in access logs and diagnostics.
5. Check the status and read the response safely
Sending a request and parsing JSON are separate steps. An API can return a JSON error document with an unsuccessful HTTP status, so successfully calling response.json() does not mean the operation succeeded. Call raise_for_status() or inspect status_code first.
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
result = response.json()
print(result)
raise_for_status() raises an HTTPError for an unsuccessful HTTP status. If you would rather branch explicitly, inspect the status:
response = requests.post(url, json=payload, timeout=10)
if 200 <= response.status_code < 300:
print("Request succeeded")
else:
print("HTTP status:", response.status_code)
print("Body:", response.text)
Some successful responses have no body. In particular, a 204 No Content response is not JSON to parse. Calling response.json() for an empty or invalid JSON body raises requests.exceptions.JSONDecodeError. Check whether a response is expected before parsing, and catch decoding errors when the response format can vary.
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
if response.status_code == 204 or not response.content:
result = None
else:
try:
result = response.json()
except requests.exceptions.JSONDecodeError:
result = response.text
Use response.text for readable text bodies and response.content for raw bytes. Be careful when printing response bodies in production: they can contain personal data, credentials, or internal error details. The official Requests Quickstart documents status checking and JSON decoding behavior.
6. Set timeouts and decide how to retry
Always set a finite timeout for network calls. Without one, a request may wait indefinitely if a remote server or connection stalls. Choose a value appropriate to the API’s expected response time and the work your application can tolerate. Requests accepts a timeout option; it is not a promise that every request finishes within exactly that many seconds in all circumstances.
response = requests.post(url, json=payload, timeout=10)
For separate connection and read limits, provide a tuple:
response = requests.post(url, json=payload, timeout=(3.05, 20))
The first value limits how long to wait while establishing a connection; the second limits waiting for data from the server. Select values based on your environment and API, rather than copying them blindly. A short timeout can fail on a slow but healthy endpoint; a long timeout can tie up a worker or user request for too long.
Retries need care for POST requests. If the server completed the operation but the response was lost, retrying may create a duplicate. Use an API’s idempotency-key mechanism when it offers one, and retry only errors that are appropriate to retry. A timeout does not prove that the server did nothing. For transient failures, use bounded retries with backoff and respect any retry guidance in the API response. Do not retry authentication, validation, or other permanent client errors without changing the request.
7. Use cURL, Python, and Node.js to send the same JSON
These examples send the same basic object to an example endpoint. Replace the URL and payload with the values in your API’s documentation. For cURL, --data sends the body and the explicit header labels it as JSON.
curl -X POST "https://api.example.com/items" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{"name":"Alice","active":true}'
In Python Requests, use json= so Requests performs the serialization:
import requests
response = requests.post(
"https://api.example.com/items",
json={"name": "Alice", "active": True},
timeout=10,
)
response.raise_for_status()
print(response.json())
In Node.js, the built-in fetch API expects you to stringify the object and set the content type:
const response = await fetch('https://api.example.com/items', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ name: 'Alice', active: true }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
const result = await response.json();
console.log(result);
These clients differ in what they do for you. Requests’ json= handles the JSON request workflow. The cURL and Node.js examples explicitly mark and serialize their bodies. In all three, you still need to check the HTTP outcome and match the endpoint’s expected schema.
8. Or skip the browser setup
If the task is taking a screenshot of a page as part of a workflow, [ScreenshotNeo](https://screenshotneo.com) is a website screenshot API. A single request returns a screenshot or PDF; the product also provides an MCP server for AI agents. Here is a Python call using the documented screenshot endpoint:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
See the ScreenshotNeo API documentation for its request options and authentication. Cookie banners, popups, and chat widgets are removed before the shot. Bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.
9. Troubleshoot common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| Unsupported media type or server says it expected JSON | The body was sent as form data, or manually serialized JSON omitted its content type. | Use json=payload. If you intentionally use data=json_text, set Content-Type: application/json. |
| Server receives an empty or unexpected body | json was combined with data or files; the JSON parameter is ignored in that case. |
Choose one body method that matches the endpoint: JSON, form data, or multipart upload. |
JSONDecodeError while parsing |
The body is empty, invalid JSON, or a different format such as HTML. A no-content response is another common case. | Check the status and response content first. Handle empty bodies and parse errors explicitly; inspect response.text while debugging. |
HTTPError from raise_for_status() |
The server returned an unsuccessful HTTP status, even if its error body is JSON. | Read the status and relevant error body, then fix authentication, validation, permissions, or endpoint usage before retrying. |
Timeout |
The connection or response took longer than the configured limit. | Check endpoint health and network conditions. Set a suitable timeout; retry only if the operation is safe or protected against duplicates. |
ConnectionError or name resolution failure |
Network interruption, DNS problem, invalid hostname, proxy issue, or unreachable server. | Verify the URL and network path, then check proxy and DNS configuration. Retry transient connection failures with limits. |
| API rejects fields despite valid JSON | JSON syntax is valid, but the schema, field names, types, or required values do not match the API. | Compare the payload against the endpoint schema. Check whether it expects an object or array and whether fields should be omitted or set to null. |
| 401 or 403 response | Missing, expired, malformed, or insufficient credentials. | Confirm the API’s authentication method, token scope, and required header. Avoid logging the token. |
When debugging, inspect the status code, response headers, and a safe portion of the response body. Do not dump secrets or full user payloads into logs. Distinguish a transport failure (no usable response) from an HTTP error (a response arrived with an unsuccessful status) and from a JSON decoding failure (the body could not be interpreted as JSON).
10. Performance, reliability, and cost considerations
For a single small JSON request, the most important performance factors are usually the remote API’s response time, network conditions, and the size of the payload. Avoid sending fields the endpoint does not need, but do not remove fields the API requires. For repeated calls to the same host, a Requests Session can reuse connections and persist settings such as headers:
import requests
with requests.Session() as session:
session.headers.update({"Accept": "application/json"})
response = session.post(
"https://api.example.com/items",
json={"name": "Alice"},
timeout=(3.05, 20),
)
response.raise_for_status()
Connection reuse does not remove the need for a timeout or status handling. Close sessions when finished, as in the context manager above. For concurrent or high-volume use, account for the API’s rate limits, quotas, and concurrency guidance; those limits are specific to the service and should not be guessed.
Retries improve resilience only when used carefully. Bound the number of attempts, add backoff to avoid repeatedly hitting a struggling service, and avoid replaying a non-idempotent operation unless the API provides a safe idempotency mechanism. Keep application-level deadlines in mind so that a retry loop does not consume more time than the caller can wait.
Requests is a client library; the request itself may have costs governed by the remote API’s pricing and usage policy. Check that provider’s current terms and monitor usage where available. The request code cannot determine whether an API charges for failed requests or retries.
11. Practical checklist
- Use
json=payloadfor a JSON API and pass a JSON-serializable Python value. - Do not combine
json=withdata=orfiles=unless you understand thatjsonis ignored. - Use
data=for form encoding; for pre-serialized JSON, set the JSON content type yourself. - Set a finite timeout that fits the API and application.
- Call
raise_for_status()or inspectstatus_codebefore treating the operation as successful. - Parse the response only if it is expected to contain JSON; handle no-content and invalid JSON responses.
- Keep credentials out of source control, URLs, and logs.
- Follow the endpoint’s schema and rate-limit guidance, and make retries safe for the operation.
12. FAQ
Can I send a list with json=?
Yes. Pass a Python list when the endpoint expects a JSON array at the top level. Confirm the required shape in the API documentation.
Does json= return a Python dictionary?
No. It controls the outgoing request body. To decode a JSON response, call response.json() after checking the HTTP status and whether a response body is present.
Should I add Content-Type when I use json=?
Usually not. Use json= for the JSON workflow. Add the header manually when you send pre-serialized JSON through data=.
Can a successful API request have no JSON response?
Yes. Some successful responses contain no body. Do not call response.json() unconditionally when the endpoint can return no content.
Which Requests version or Python version should I use?
Check the official Requests documentation for current supported versions and installation guidance. The documentation identifies the supported Python versions and current release; those details can change over time.
References
- Requests API Reference: request parameters including
json,data,files, andtimeout. - Requests Quickstart: JSON requests, form data, response status, and JSON decoding.


