Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand Grape API route param

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?

like image 287
kcg5544 Avatar asked Jul 09 '15 17:07

kcg5544


1 Answers

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
like image 69
Marlon Avatar answered Oct 20 '22 17:10

Marlon