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?
As query parameters are not a fixed part of a path, they can be optional and can have default values.
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.
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.
Simply requiredBy default, query parameters are required, so simply defining them makes them required.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With