Question

I am looking for clarification on the syntax to declare API resource paths in Grape. The example below declares the resource paths "/items", "/items/:id", "/objects", and "/objects/:id". What I do not undestand is why the definition for "/items/:id" returns null?

class API < Grape::API

  format :json
  default_format :json

  rescue_from :all, backtrace: true


  resource :items do

    desc "Returns an array of all items."
    get do
      ITEMS.find.to_a
    end

    desc "Returns an item by its id."
    get '/:id' do

      # hardcoding the document id returns the correct document
      # ITEMS.find_one( "item_id" => 2519 )

      # using the path parameter :id returns null, why???
      ITEMS.find_one( "item_id" => params[:id] )
    end
  end


  resource :objects do

    desc "Returns an array of all objects."
    get do
      OBJECTS.find.to_a
    end

    ##
    # using the route_param syntax correctly returns the document
    # resource path /objects/:id
    ##
    desc "Returns an object by its id."
    params do
      requires :id, type: Integer
    end
    route_param :id do
      get do
        OBJECTS.find_one( "object_id" => params[:id] )
      end
    end
  end

end
Was it helpful?

Solution

Your use of resource and route methods is ok.

You have a problem with parameter processing - params[:id] is a String by default. Your example hard-coded value that works is aFixnum (integer).

Probably your (not shown) code that queries the list on ITEMS is looking up integer values.

You could use ITEMS.find_one( "item_id" => params[:id].to_i ) to convert the param inline.

However, you probably should use a params description block to get Grape to convert for you, as you already are for OBJECTS:

desc "Returns an item by its id."
params do
  requires :id, type: Integer
end
get '/:id' do
  ITEMS.find_one( "item_id" => params[:id] )
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top