How to POST JSON Data With cURL?

In this article, lets discuss on what is cURL and how to make an POST API call using cURL.

cURL

cURL is the powerful command line tool that allows you to transfer data across the network.


cURL supports lot of protocols like HTTP, HTTPS, FTP, SMTP, IMAP and more. It is accessible on windows, Mac, Linux making a best choice for developers across all the platforms.

POST API call using cURL

curl -d '{"name":"sam", "id":"01"}' -H "Content-Type: application/json" -X POST https://www.java.ws/employee

Syntax explanation
curl -> command
-d -> data to be sent over the network (optional)
-H -> header information (optional)
-X -> custom request method, GET will behave as the default method

Examples

cURL Post Request With No Data

     curl -X POST https://www.java.ws/employee

cURL Post Request With json Content

      curl -d '{"name":"sam", "id":"01"}' -H "Content-Type: application/json" -X POST https://www.java.ws/employee

cURL POST With a File

      curl -d "@data.json" -X POST http://www.java.ws/employee

Below is the sample json which can be passed in the parameter data.json:

         {"name":"sam", "id":"01"}

In cURL POST API call with -data option will implicitly make a default header which looks like Content-Type: application/x-www-form-url encoded. This content type is what your typical browser will use for a plain POST but Spring application will not accept. So you need to include -H tag to specify the content-type explicitly.

Conclusion

To summarize, we’ve seen how to post data using cURL with various options.