curl POST with JSON Body
Master curl POST requests with JSON payloads. Learn Content-Type headers, data formatting, file input, and the --json shortcut for sending structured data.
Detailed Explanation
Sending JSON with curl POST
POST requests with JSON bodies are the backbone of modern API communication. curl makes it straightforward to send structured data to any endpoint.
Basic JSON POST
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'
The -X POST flag sets the HTTP method, -H adds the Content-Type header, and -d provides the request body.
Reading JSON from a File
For larger payloads, read the JSON body from a file using the @ prefix:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @payload.json
Using --json Flag (curl 7.82+)
Modern versions of curl include a --json shortcut that automatically sets the Content-Type and Accept headers:
curl --json '{"name": "Alice"}' https://api.example.com/users
This is equivalent to setting -H "Content-Type: application/json", -H "Accept: application/json", and -d all at once.
Escaping and Quoting
When working with JSON in shell scripts, quoting can become tricky. Use single quotes around the JSON string to avoid shell interpolation issues:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"count": 42, "active": true, "tags": ["admin", "user"]}'
If you need to include shell variables, switch to double quotes and escape the inner quotes:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d "{"name": "$USER_NAME"}"
Verifying the Request
Always pair POST requests with -v (verbose) during development to inspect the full request and response cycle, including headers and status codes. To verify your JSON is well-formed before sending, pipe it through jq first.
Use Case
A backend developer needs to create new resources through a REST API by sending structured JSON data, such as creating user accounts or submitting form data.