EN
Bash - send HTTP POST request with JSON body using curl
13
points
In this short article, we would like to show how to send HTTP POST request with JSON body/payload using curl
under Bash.
Quick solution:
echo '{"name":"john"}' | curl -X POST -H "Content-Type: application/json" -d @- http://localhost:80/path/to/rest/api
to untrusted HTTPS server:
echo '{"name":"john"}' | curl -k -X POST -H "Content-Type: application/json" -d @- https://localhost:443/path/to/rest/api
Where:
-k
lets to request servers with untrusted certificates (e.g.localhost
),-X POST
indicates request method,-H "Content-Type: application/json"
informs server API about sent content type,-d @-
lets to use stdin and send them JSON data (-d @-
is shortcut for--data-binary @-
).
Alternative solution
We can send JSON payload from indicated file using:
curl -X POST -H "Content-Type: application/json" -d @/path/to/data.json http://localhost:80/path/to/rest/api
Where:
-d @/path/to/data.json
indicates a file that contains JSON to send inside the body of the POST request.
Example /path/to/data.json
file content:
{
"name": "john"
}