3

Is it possible to give optional URL parameter in grape route.

Ie. for a an endpoint like :

    get '/user/:name/:location/:id' do
    end

Is there any way to hit this endpoint with or without "location" parameter in the URL.

I tried defining endpoint with bracket for optional parameter as below :

    get '/user/:name/(:location)/:id' do
    end

But this did not work

Hridya
  • 236
  • 2
  • 12

1 Answers1

0

I would suggest that you use location as a query param. So that you'll be able to make it optional and to keep just 1 route.

params do
  optional :location, type: String
end

get '/user/:name/:id' do
  if params[:location].present?
    # some code
  else
    # some code
  end
end

This route will be matched by /user/:name/:id?location={something} with a location, and /user/:name/:id without.

Brozorec
  • 1,163
  • 9
  • 15