Search code examples
ruby-on-railsruby-grapegrape-api

Attributes is missing (grape API)


I'm newbie in Rails. I tried to write a small API Rails application use gem grape.

I followed up this tutorial http://www.sitepoint.com/build-great-apis-grape/

But when i tried to create a new record, i had an error as: {"error":"type_id is missing"}

Here is my code:

singers.rb

module V1
 class Singers < Grape::API
  resource :singers do
    desc "List all singers"
    get do
      Singer.all
    end

    desc "Create a new singer"
    params do
      requires :name, type: String
      requires :type_id, type: Integer
    end

    post do
      Singer.create!({
       name: params[:name],
       type_id: params[:type_id]
      })
    end
  end
 end
end

And when i type in console as: curl http://localhost:3000/api/v1/singers.json -d "name=khanhpn;type_id=1"

I had an error: {"error":"type_id is missing"}

I didn't understand why it throw error. Hope everybody can explain for me. Thank you very much.

This is my code which i pushed on bitbucket: https://bitbucket.org/baran19901990/grape_api/src/b8a0d676f17de3fedc95cc7efff60fab5afb0fc1/app/api/v1/singers.rb?at=master&fileviewer=file-view-default

Solutions:

curl -X POST http://localhost:3000/api/v1/singers -d "name=khanhpn&type_id=1"


Solution

  • The problem is in passing your parameters to curl. You have to separate them by & and not ; curl http://localhost:3000/api/v1/singers.json -d "name=khanhpn&type_id=1"