The curl
command line utility is a powerful tool for making HTTP requests. It can be used to send a variety of different HTTP requests, including POST requests with a JSON body. Here’s how you can use curl to send a POST request with a JSON body:
Create a JSON fileCreate a JSON file that contains the data you want to send in the request body. For example, let’s say you have a file named data.json
with the following contents: { “name”: “John Doe”, “age”: 25 }1234{ “name”: “John Doe”, “age”: 25} Curl POST DataUse the curl command to send a POST request with the JSON data. The -X
option specifies the request method (in this case, POST), and the -H
option adds an HTTP header (in this case, Content-Type: application/json
to specify that the request body is in JSON format). The -d option specifies the request body, and the @
symbol tells curl to read the data from a file.Here’s the command to send the POST request with the JSON data:curl -X POST -H “Content-Type: application/json” -d @data.json http://example.com/endpoint Curl POST Data with Response HeaderIf the request is successful, the server will return a response. You can use the -i
option to include the response headers in the output, or the -o
option to save the response to a file.Here’s an example of using the -i
option to print the response headers:curl -X POST -H “Content-Type:application/json” -d @data.json http://example.com/endpoint -i And here’s an example of using the -o
option to save the response to a file:curl -X POST -H “Content-Type: application/json” -d @data.json http://example.com/endpoint -o response.txt
That’s all there is to it! With these simple commands, you can use curl
to send a POST request with a JSON body to a server.
Here’s the command to send the POST request with the JSON data:
Here’s an example of using the -i
option to print the response headers:
And here’s an example of using the -o
option to save the response to a file:
Keep in mind that the JSON data in the request body must be properly formatted and valid, or the request may fail. You can use a tool like JSONLint (https://jsonlint.com/) to validate your JSON data before sending it in the request.
I hope this tutorial has been helpful in showing you how to use curl
to send a POST request with a JSON body. If you have any questions or need further assistance, don’t hesitate to ask.