Search code examples
ruby-on-railsrestcurlhttp-postnested-resources

HTTP POST request sent via curl against REST server looses JSON parameters


I created a REST server with Rails that manages Users and associated Comments.
Here is the routes configuration.

resources :users do
  resources :comments
end

In the controller I only need actions to query and create Comments. The exchange format is JSON.

class CommentsController < ApplicationController

  def index
    @user = User.find(params[:user_id])
    @comments = @user.comments  
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @comments }
    end
  end

  def create
    @user = User.find(params[:user_id])
    @comment = @user.comments.create!(params[:comment])
    redirect_to @user
  end

end

I would like to store Comments created by a remote client. It is an Android application. To test the server I am trying the following curl commands, as suggested here.

curl -X POST -d @comment1.json http://localhost:3000/users/42/comments
curl -X POST -d @comment1.json http://localhost:3000/users/42/comments.json
curl -X POST -d @comment2.json http://localhost:3000/users/42/comments
curl -X POST -d @comment2.json http://localhost:3000/users/42/comments.json

I am also not sure how the JSON file has to look like. Here are the variations I tried:
comment1.json

{
  content:
  {
    message: "Let's see if this works.",
    subject: "JSON via curl"
  }
}

... or comment2.json

{
  message: "Let's see if this works.",
  subject: "JSON via curl"
}

When I check the Comments on the particular User I can see that it has been created, however, the parameters subject and message, I passed, get lost somewhere!

[
  {
    created_at: "2012-08-11T20:00:00Z",
    id: 6,
    message: "null",
    subject: "null",
    updated_at: "2012-08-11T20:00:00Z",
    user_id: 42
  }
]

The Rails installation includes the following gems.

...
Using multi_json (1.3.6) 
Using json (1.7.4)
...

Question:

  • How can I test the creation of Comments via curl or with any other suitable tool?

Solution

  • Try setting the content-type header with -H "Content-Type:application/json". I think Rails is looking for the post parameters as form data (eg. content[subject]='JSON via curl').

    Further, the JSON file is not valid. JSON keys need to be quoted, too. Use the following file ...

    {
      "message": "Let's see if this works.",
      "subject": "JSON via curl"
    }
    

    and send it with one of these commands ...

    curl -X POST -H "Content-Type:application/json" -d @comments2.json http://localhost:3000/users/42/comments
    curl -X POST -H "Content-Type:application/json" -d @comments2.json http://localhost:3000/users/42/comments.json