Reputation: 13987
When designing a HTTP RESTful API is it ok to have parameters with default values when they are omitted? or is that confusing?
for example:
/posts?categories=20,21,18
is missing a limit
parameter, so we set the limit to limit=100
by default
/posts?categories=20,21,18&limit=200
sets the limit to 200 overriding the default.
Is it okay to have defaults for params in an API? or will this simply confuse developers trying to understand the API? Should default params responsibility be on the client consuming the API?
Upvotes: 0
Views: 3190
Reputation: 1
It very ok to specify default if you know that the caller of the endpoint may omit the parameter in the url. This way codes will not be broken.
Upvotes: 0
Reputation: 108
While the answer to this question largely depends on the circumstance, providing reasonable defaults is very common.
For example, we can look at how Google does things with their search. When searching for cats you can use their q
parameter: https://www.google.com/search?q=cats. Google won't return all 635,000,000 results because you didn't specify a limit, they make a reasonable assumption that they can limit the results to a set number and wait for you to request more.
Looking further into your example, you really only have two options for when the client consuming your API omits the limit param:
Generally you want to avoid returning errors unless something actually goes wrong (for instance if the endpoint has a required field that is essential to the process).
So we set a default. In the case of the limit
param, aside for responding with an error, there is no way to avoid setting a default. Whether you respond with every possible entry, 100 entries, 1 entry, or none, all of those are a type of default. In essence, not choosing is a choice.
Upvotes: 1
Reputation: 828
Of course it is ok. And it won't confuse devs as long as your documentation is well maintained and shows what parans are required and which one have default values. Have a look at the rest api docs of GitLab for example.
Upvotes: 0