I set up a simple new rails application with model entry, with attributes title
and content
using scaffolding.
now I am trying to use curl to POST the JSON data (rather than using the browser).
the following seems to work (i.e. successfully posted with null data):
curl --verbose --header "Accept: application/json" --header "Content-type: application/json" --request POST --data "" http://localhost:3000/entries
the following does not work:
curl --verbose --header "Accept: application/json" --header "Content-type: application/json" --request POST --data "{'content':'I belong to AAA','title':'AAA'}" http://localhost:3000/entries
I have tried many variations. the errors I get are mostly host not found or unexpected token at the JSON data.
To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.
To post data in the body of a request message using Curl, you need to pass the data to Curl using the -d or --data command line switch. The Content-Type header indicates the data type in the body of the request message.
by David Callaghan on January 20th, 2022 | ~ 3 minute read. cURL is frequently used by developers working with REST API's to send and receive data using JSON notation.
Syntax. By default, curl will perform a GET request. So, if you're running your API on localhost:3000, you could type curl http://localhost:3000/users in the command line to run a GET request, and you would receive a JSON object containing all of the users in your database.
To go along with what Jonathan said, the Post is now sending the data to the EntriesController. Now in your create
action you have to get the data from the params
hash. I am going to assume you are doing it the railsy way and so you would do something like this:
curl -d 'entry[content]=I belong to AAA' -d entry[title]=AAA http://localhost:3000/entries'
In your controller
Entry.create(params[:entry])
This says grab the "entry" data from the params hash (created by rails for you) and pass it as a parameter to Entry to initialize a new Object. "create" will do a "new" and "save" for you in one method call.
I ran a test and got the error MultiJson::DecodeError (743: unexpected token at '{'content':'I belong to AAA','title':'AAA'}'):
JSON requires double quotes for keys and strings, not single quotes. Try --data '{"content":"I belong to AAA","title":"AAA"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With