Search code examples
ruby-on-railsgrape-api

How to debug grape api


module Employee
    class Data < Grape::API
        resource :employee_data do 
            desc "Description of all employees"
            get do 
                EmpDatum.all
            end

            desc "create a new employee"
                params do 
                    requires :name, type: String
                    requires :address, type: String
                    requires :age, type: Integer
                end
                post  do
                    EmpDatum.create!({
               name: params[:name],
               address: params[:address],
               age: params[:age]

                        })
                end
            end
    end
end

Get request is working fine. However when sent a POST request,

curl http://localhost:3000/api/v1/employee_data.json -d "name='jay';address='delhi';age=25"

{"error":"address is missing, age is missing"}%      

I am unable to put byebug in the above post block. I am unable to see the params that are getting passed. What am I missing here


Solution

  • Nothing is wrong with your API implementation. However, you're using cURL incorrectly. Make a call like this:

    curl -i -X POST -H "Content-Type:application/json" http://localhost:3000/api/v1/employee_data.json -d '{"name":"jay","address":"Delhi","age":"25"}'
    

    Moreover, I'm not sure what bybug is but I've been using RubyMine for a while and it's perfect to debug Ruby Grape APIs. If you're not successful using bybug you can see what you're receiving in your API method just replacing your method code with this:

    puts params.inspect
    

    For example:

    module Employee
        class Data < Grape::API
            resource :employee_data do 
                desc "Description of all employees"
                get do 
                    EmpDatum.all
                end
    
                desc "create a new employee"
                params do 
                    requires :name, type: String
                    requires :address, type: String
                    requires :age, type: Integer
                end
                post  do
                    puts params.inspect
                end
            end
        end
    end