Skip to content
shellhacks.dev
Network

Send JSON in a POST Request with curl

Send JSON with curl -H 'Content-Type: application/json' -d '{...}'. Plain -d labels the body as a form, and curl 7.82 added --json to set both headers.

1 min read
Summarize in AI

A JSON body sent with curl -d reaches the API labelled as a form, and strict servers answer with a 415 or ignore the fields.

Shell
curl -s -d '{"name":"ada"}' http://127.0.0.1:8000/api | sed -n '2p;4p'
echo ---
curl -s -H 'Content-Type: application/json' -d '{"name":"ada"}' http://127.0.0.1:8000/api | sed -n '2p;4p'
echo ---
curl -s --json '{"name":"ada"}' http://127.0.0.1:8000/api | sed -n '2p;4p'
Text
Content-Type: application/x-www-form-urlencoded
body: {"name":"ada"}
---
Content-Type: application/json
body: {"name":"ada"}
---
Content-Type: application/json
body: {"name":"ada"}

-d sends the data as the body of a POST and sets Content-Type: application/x-www-form-urlencoded unless you override it, as the first block of output shows from a server that echoes what it received. Adding the header fixes the label. --json is shorthand for the header, an Accept: application/json header and the data, and it is described in the curl manual.

--json needs curl 7.82 or later, so an older machine needs the long form. Neither option checks that the text is valid JSON. For a body in a file use -d @body.json, which strips newlines with -d but keeps them with --data-binary. In the shell, single quotes keep the double quotes in the JSON intact; on Windows cmd the quoting differs.

Share

More snippets

Network

Send Form Data with curl Using -d or -F

Send form fields with curl -d for urlencoded bodies and -F for multipart. A plus sign sent with -d arrives as a space, so encode values with --data-urlencode.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.