POST JSON data to simple rails application with curl
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.
curl json post request via terminal to a rails app
First off, there is an extraneous " at the end of your command.
Try this
curl -v \
-H "Accept: application/json" \
-H "Content-type: application/json" \
-X POST \
-d ' {"user":{"first_name":"firstname","last_name":"lastname","email":"email@email.com","password":"app123","password_confirmation":"app123"}}' \
http://localhost:3000/api/1/users
How to POST to Rails with cURL?
I recommend that you avoid the JSON syntax problems and escaping needed for the shell by putting the JSON input into a file. If the file is named params.json
then use -d @params.json
to pass it from a file.
As for authentication, I'm not sure this is a good idea either but you might find a session key and pass it in the cookie header. If you are using database sessions (which is a good idea) then it will be the value in the column for the session in your database. If not then use dev tools and get your session from the browser.
Curl JSON POST request to Rails app
As @ma_il said my parameters are available in DataController as params[:datum]
, I have searched a bit more about params in Rails 5.1 which I am using and discovered that my full amswer is:
def create
my_hash = params[:datum].permit!
render json: my_hash.to_h.collect { |keys, values| "#{keys}{values.reverse}" }
end
POST JSON data with Curl Multi from ruby
Do that:
urls = [
{
:url => "http://localhost:5000/",
:method => :post,
:headers => {'Accept' => 'application/json', 'Content-Type' => 'application/json'},
:post_fields => {},
:post_body => {'field1' => 'value1', 'k' => 'j'}.to_json,
}
]
The problem: curb doesn't know that you are sending a JSON data. Curb don't read and interprets the contents of :headers
. As you can see here, curb transforms your hash into a string separated by "&", which is the default for a normal (non-json) http data sending (eg.: "field1=value1&k=j"). When the server (Rails) read and interprets the header explicity saying that the data is in JSON format, it tries to decode and the result is the same exception that you get when you do that: JSON.parse("field1=value1&k=j")
.
To solve this, you need to send "post_fields" as an empty hash, and send your actual data by using "post_body". Also, you need to convert your hash to json manually with to_json
.
I don't know if they (the curb project owners) know this problem, but I suggest you to warning them about it.
POST request using CURL for Rails App
With respect to the conversation above, let me write an answer.
If you see a form in rails, it will have a line as mentioned below
<input name="authenticity_token" type="hidden" value="+wFCV3kv0X/WI0qb54BgYlDzi+Tp+6HIGM61a4O6gg0=">
Now, if in ApplicationController
you have this line protect_from_forgery
then it would always expect authenticity_token
and if its not available, it will throw the error thats mentioned in your logs hence I suggested to remove that line because you won't be passing an authenticity_token
as a param from you api POST
requests.
The reason why your get request is working just fine is because rails doesn't expect authenticity_token
on a GET
request.
Now, you said you removed protect_from_forgery
but you got an internal server error, well that has to be handled by you as it has got nothing to do with GET
or POST
request but it is an error in your rails application. So solve that error and it should work just fine. Or also post the error log here so may be I can help you with that.
EDIT: Solution to your internal server 500 error
With the logs pasted below, it is also necessary that you allow the attributes in your controller, just as @abhinay mentioned in the code.
Hope that helps
Curl Post JSON format to ActiveStorage in Rails with image
my example is not same your image model.
but you can change you code after show my example code
https://github.com/x1wins/tutorial-rails-rest-api/blob/master/README.md#active-storage
model
class Post < ApplicationRecord
has_many_attached :files
end
controller
# posts_controller
# POST /posts
def create
@post = Post.new(post_params)
@post.files.attach(params[:post][:files]) if params.dig(:post, :files).present?
set_category @post.category_id
if @post.save
render json: @post, status: :created, location: api_v1_post_url(@post)
else
render json: @post.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /posts/1
def update
@post.files.attach(params[:post][:files]) if params.dig(:post, :files).present?
if @post.update(post_params)
render json: @post
else
render json: @post.errors, status: :unprocessable_entity
end
end
# DELETE /posts/:id/attached/:id
def destroy_attached
attachment = ActiveStorage::Attachment.find(params[:attached_id])
attachment.purge # or use purge_later
end
curl
curl -F "post[body]=string123" \
-F "post[category_id]=1" \
-F "post[files][]=@/Users/rhee/Desktop/item/log/47310817701116.csv" \
-F "post[files][]=@/Users/rhee/Desktop/item/log/47310817701116.csv" \
-X POST http://localhost:3000/api/v1/posts
How can I post JSON data with curl and use it in RoR?
According to this:
if you’ve turned on config.wrap_parameters in your initializer or
calling wrap_parameters in your controller, you can safely omit the
root element in the JSON/XML parameter. The parameters will be cloned
and wrapped in the key according to your controller’s name by default.
So, my guess is that you either need to include a root element, or set config.wrap_parameters
.
Related Topics
What Alternatives to Irb Are There
Ruby Methods That Either Yield or Return Enumerator
Ruby on Rails, Two Models in One Form
Reading the First Line of a File in Ruby
Rails - How to Check Developer Mode or Production Mode in Code
What Is the Easiest Way I Can Create a 'Beep' Sound from a Ruby Program
Convert Datetime String to Utc in Rails
How to Log the Entire Trace Back of a Ruby Exception Using the Default Rails Logger
Rails 5.2 Active Storage Add Custom Attributes
What Is Double Method in Rspec For
Find Records with Datetime That Match Today's Date - Ruby on Rails
Which Ruby Memoize Pattern Does Activesupport::Memoizable Refer To