To POST JSON data using cURL, use the -H flag to set the Content-Type header to application/json and the -d/--data flag to include the JSON payload. Here’s how to do it:
Basic Command
curl -X POST \
-H "Content-Type: application/json" \
-d '{"key": "value", "nested": {"data": true}}' \
https://api.example.com/endpoint
Key Options
-X POST: Explicitly sets the HTTP method to POST (optional if using-d).-H "Content-Type: application/json": Specifies the request body is JSON.-d '{"key": "value"}': Provides the JSON payload (use single quotes to avoid shell escaping issues).
Send JSON from a File
For large JSON payloads, read from a file:
curl -X POST \
-H "Content-Type: application/json" \
--data-binary @data.json \
https://api.example.com/endpoint
@data.json: Loads JSON from the filedata.json.
Include Headers (e.g., Authentication)
curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{"query": "test"}' \
https://api.example.com/secure
Handle Responses
- Print response headers: Add
-i. - Save output to a file: Add
-o response.json. - Verbose mode: Add
-vfor debugging.
Example:
curl -X POST -i \
-H "Content-Type: application/json" \
-d '{"status": "ok"}' \
-o response.json \
https://api.example.com/endpoint
Common Errors
- Syntax Issues:
- Use single quotes (
') around JSON to avoid shell expansion. - Validate JSON with tools like JSONLint.
- Missing Headers:
- Ensure
Content-Type: application/jsonis included.
- Escaping Special Characters:
- For complex JSON, escape double quotes with
\or use a file:bash -d "{\"key\": \"value\"}"
Example Workflow
- Create a JSON file (
payload.json):
{
"name": "Alice",
"age": 30,
"active": true
}
- Send the request:
curl -X POST \
-H "Content-Type: application/json" \
--data-binary @payload.json \
https://api.example.com/users
Verify with Tools
Test your endpoint first with tools like:
This method works for APIs, webhooks, and services expecting JSON input. Always check the API documentation for specific requirements!