rest - How do I POST JSON data with cURL?

ID : 145

viewed : 233

Tags : jsonrestspring-mvccurlhttp-headersjson

Top 5 Answer for rest - How do I POST JSON data with cURL?

vote vote


You need to set your content-type to application/json. But -d (or --data) sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

Looking at the curl man page, I think you can use -H (or --header):

-H "Content-Type: application/json" 

Full example:

curl --header "Content-Type: application/json" \   --request POST \   --data '{"username":"xyz","password":"xyz"}' \   http://localhost:3000/api/login 

(-H is short for --header, -d for --data)

Note that -request POST is optional if you use -d, as the -d flag implies a POST request.

On Windows, things are slightly different. See the comment thread.

vote vote


Try to put your data in a file, say body.json and then use

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf 
vote vote


For Windows, having a single quote for the -d value did not work for me, but it did work after changing to double quote. Also I needed to escape double quotes inside curly brackets.

That is, the following did not work:

curl -i -X POST -H "Content-Type: application/json" -d '{"key":"val"}' http://localhost:8080/appname/path 

But the following worked:

curl -i -X POST -H "Content-Type: application/json" -d "{\"key\":\"val\"}" http://localhost:8080/appname/path 
vote vote


You might find resty useful:

It's a wrapper round CURL which simplifies command line REST requests. You point it to your API endpoint, and it gives you PUT and POST commands. (Examples adapted from the homepage)

$ resty #Sets up resty to point at your endpoing $ GET /blogs.json                  #Gets                                    #Put JSON $ PUT /blogs/2.json '{"id" : 2, "title" : "updated post", "body" : "This is the new."}'                                    # POST JSON from a file $ POST /blogs/5.json < /tmp/blog.json 

Also, it's often still necessary to add the Content Type headers. You can do this once, though, to set a default, of add config files per-method per-site: Setting default RESTY options

vote vote


It worked for me using:

curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"id":100}' http://localhost/api/ 

It was happily mapped to the Spring controller:

@RequestMapping(value = "/postJsonReader", method = RequestMethod.POST) public @ResponseBody String processPostJsonData(@RequestBody IdOnly idOnly) throws Exception {         logger.debug("JsonReaderController hit! Reading JSON data!"+idOnly.getId());         return "JSON Received"; } 

IdOnly is a simple POJO with an id property.

Top 3 video Explaining rest - How do I POST JSON data with cURL?