8

I am having a lot of trouble understanding Grape API, specifically route_param and how it works with just params.

Consider this code:

desc "Return a status."
params do
 requires :id, type: Integer, desc: "Status id."
end
route_param :id do
 get do
  Status.find(param[:id])
 end
end

What route does this block produce? I get that this is a get request, but why is it wrapped in route_param block? Why can't it be in params block?

approxiblue
  • 6,982
  • 16
  • 51
  • 59
kcg5544
  • 203
  • 3
  • 5

1 Answers1

13

Your block produces this route:

http://yourdomain.com/<resource>/<id>

Note that your code and the code below do the same thing and produce the same route:

desc "Return a status."

params do
  requires :id, type: Integer, desc: "Status id."
end

get ':id' do
  Status.find(params[:id]) 
end

You can use route_param to group methods that receive the same params, for example:

resource :categories do
  route_param :id do
    get do # produces the route GET /categories/:id
    end

    put do # produces the route PUT /categories/:id
    end
  end
end
approxiblue
  • 6,982
  • 16
  • 51
  • 59
Marlon
  • 888
  • 6
  • 12