30

I am using Curl from the command line to debug a small web api I am working on. The web api expects basic authentication and a JSON object as input (POST). Currently this basic authentications works fine:

curl -i --user validuser:70e12a10-83c7-11e0-9d78-0800200c9a65 http://example.com/api.php

but I also want to send a JSON object as a POST request:

curl -i --user validuser:70e12a10-83c7-11e0-9d78-0800200c9a65 -X POST -d '{"person":{"name":"bob"}}' http://example.com/api.php

I'm getting a 400 Bad Request response with the above command, any ideas on how I bundle a json object in this POST request?

Twobard
  • 2,553
  • 1
  • 24
  • 27

3 Answers3

59

Try it with:

curl -i --user validuser:70e12a10-83c7-11e0-9d78-0800200c9a65 -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"person":{"name":"bob"}}' http://mysite.com/api.php

I've removed the json= bit in the body content.

Alternatively, this post might be helpful: How to post JSON to PHP with curl

Community
  • 1
  • 1
Jits
  • 9,647
  • 1
  • 34
  • 27
6
curl --request POST \
  --url http://host/api/content/ \
  --header 'authorization: Basic Esdfkjhsdft4934hdfksjdf'
4F2E4A2E
  • 1,964
  • 26
  • 28
1

Don't use

$person = file_get_contents("php://input");

instead use

$person = $_POST['person'];

And if you're using curl from the command-line this is the syntax for wanting to POST json data:

curl -d 'person={"name":"bob"}'
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
  • 1
    From the various threads i've read on this topic, file_get_contents("php://input"), appears to be the standard way of retrieving the raw body of the post request. – Twobard May 24 '11 at 12:06
  • @LBNerdBard define "standard". – Luca Matteis May 24 '11 at 12:07
  • I should have said 'most sensible' instead of 'standard', because I am not processing multipart form data but rather a single string entity – Twobard May 24 '11 at 12:13
  • If this method is possible, could you produce the full (basic authenticated) curl command corresponding to it, i have changed the api to listen for $_POST['person'] - This question is not just how to accept JSON data, but how to construct the fully authenticated curl POST command – Twobard May 24 '11 at 12:28