Can't understand Grape API route param
Asked Answered
P

1

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?

Politics answered 9/7, 2015 at 17:0 Comment(0)
R
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
Rupiah answered 10/7, 2015 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.