[json] How to pass payload via JSON file for curl?

I can successfully create a place via curl executing the following command:

$ curl -vX POST https://server/api/v1/places.json -d "
  auth_token=B8dsbz4HExMskqUa6Qhn& \
  place[name]=Fuelstation Central& \
  place[city]=Grossbeeren& \
  place[address]=Buschweg 1& \
  place[latitude]=52.3601& \
  place[longitude]=13.3332& \
  place[washing]=true& \
  place[founded_at_year]=2000& \
  place[products][]=diesel& \
  place[products][]=benzin \
"

The server returns HTTP/1.1 201 Created.
Now I want to store the payload in a JSON file which looks like this:

// testplace.json
{
  "auth_token" : "B8dsbz4HExMskqUa6Qhn",
  "name" : "Fuelstation Central",
  "city" : "Grossbeeren",
  "address" : "Buschweg 1",
  "latitude" : 52.3601,
  "longitude" : 13.3332,
  "washing" : true,
  "founded_at_year" : 2000,
  "products" : ["diesel","benzin"]
}

So I modify the command to be executed like this:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json

This fails returning HTTP/1.1 401 Unauthorized. Why?

This question is related to json curl

The answer is


curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.