Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API required parameters in query string?

Tags:

rest

When designing a RESTful API, what to do if a GET request only makes sense if there are specific parameters associated with the request? Should the parameters be passed as a query string, and if so, what to do when all the parameters aren't specified or are formatted incorrectly?

For example, lets say i have a Post resource, which can be accessed by `api/posts` endpoint. Each post has a geographical location, and posts can be retrieved ONLY when specifying an area that the posts may reside in. Thus, 3 parameters are required: latitude, longitude and radius.

I can think of 2 options in this case:
1. Putting the parameters in query string: api/posts/?lat=5.54158&lng=71.5486&radius=10
2. Putting the parameters in the URL: api/posts/lat/5.54158/lng/71.5486/radius/10

Which of these would be the correct approach? It seems wrong to put required parameters in the query string, but the latter approach feels somewhat 'uglier'.

PS. I'm aware there are many discussion on this topic already (for example: REST API Best practices: Where to put parameters?), but my question is specifically addressed to the case when parameters are required, not optional.

like image 429
stensootla Avatar asked Feb 18 '15 18:02

stensootla


People also ask

CAN REST API have query parameters?

You can use query parameters to control what data is returned in endpoint responses. The sections below describe query parameters that you can use to control the set of items and properties in responses, and the order of the items returned.

Can a query parameter be required?

Query parameters are the most common type of parameters. They appear at the end of the request URL after a question mark ( ? ), with different name=value pairs separated by ampersands ( & ). Query parameters can be required and optional.

How do I make query string mandatory?

The first solution to make query string parameters mandatory is to use Model Binding on the public properties of a class. We make the Number property mandatory by using the [BindRequired] attribute.


1 Answers

The first approach is better.

api/posts/?lat=5.54158&lng=71.5486&radius=10 



The second approach is a little misleading.

api/posts/lat/5.54158/lng/71.5486/radius/10 

You should think of each of your directories as resources. In this cause, sub-resources (for example: "api/posts/lat/5.54158") are not really resources and thus misleading. There are cases where this pattern is a better solution, but looking at what's given, I'd go with using the query string. Unless you have some entity linking to link you directly to this URL, I don't really like it.

like image 151
Isaiah van der Elst Avatar answered Sep 17 '22 09:09

Isaiah van der Elst