Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinatra with optional query parameters

I want to create a Sinatra API route with optional query parameters.I'm able to add the query parameters as follows

%r{^/mysql/data/(?)/start_time=(?\w*)/?}

But the route corresponding to the above route is like "/mysql/data/:name/start_time=:start_time"

I need the query parameters as optional and to be declared in URL format.

Eg:

/mysql/data/:name?start_time=:start_time&end_time=:end_time

Is there any way in Sinatra to do this?

like image 614
NagaLakshmi Avatar asked Aug 12 '14 07:08

NagaLakshmi


People also ask

Can query parameters be optional?

As query parameters are not a fixed part of a path, they can be optional and can have default values.

Can post Endpoint have query parameters?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec. "Why do you pass it in a query param?" Because, like for GET requests, the query parameters are used to refer to an existing resource.

Are query params always optional?

All common query parameters are optional query parameters unless stated otherwise in a specific API documentation. Pagination parameter that specifies the page number of results to be returned. Used in conjunction with $pagesize . Pagination parameter that specifies the number of results per page.

Should query params be mandatory?

Simply requiredBy default, query parameters are required, so simply defining them makes them required.


1 Answers

Quoting from the Sinatra Docs:

# Routes may also utilize query parameters:

get '/posts' do
  # matches "GET /posts?title=foo&author=bar"
  title = params[:title]
  author = params[:author]
  # uses title and author variables; query is optional to the /posts route
end

In your case simply use /mysql/data/:name, any query parameters will be available via params automatically.

like image 177
branch14 Avatar answered Oct 12 '22 01:10

branch14