Reputation: 1234
I'm new to REST API and I'm creating endpoints right now for my project. My question is?
What is the right approach in creating an endpoint for multiple record. Instead of doing this
/users/:id
I want to select multiple users like in sql
"where users.id in [ ]"
Is it correct to create an endpoint like this:
/users?user_id=1,2,3
selecting users with ID of 1,2 and 3?
Upvotes: 0
Views: 2710
Reputation: 728
Besides query parameters you can also use matrix parameters. Matrix parameters have the advantage that they clearly belong to a specific part of the URL. Consider the following:
/users;id=1,2,3/messages
This would return the list of messages belonging to the users 1, 2 and 3.
With a query parameter it would look like this:
/users/messages?users=1,2,3
This works but it's rather strange. Query parameters don't communicate which part of the URL they belong to.
The drawback is that framework support for matrix parameters is varying. Some support them, some don't.
I'd like matrix parameters best here but a query parameter is OK, too.
For list-like parameters, there are two ways to specify them: You can repeat the parameter name or separate different values by a comma. Both is possible and some frameworks prefer the one, some frameworks prefer the other. This is true for both matrix and query parameters.
Upvotes: 2
Reputation: 1136
If you have an HTML form that allows multiple selections, like the example below, the browser performs the GET
request as Rolson Quadras mentioned (/search?q=volvo&q=opel
).
<form action="/search" method="GET">
<select multiple name="q">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button type="submit">Search</button>
</form>
Now, it is up to the server implementation to understand what's being sent. Rails, for example also understands /search?q[]=volvo&q[]=opel
(note the square brackets used to indicate an array).
Upvotes: 1
Reputation: 446
You can have a list in your code to get the list of user ids from query Parma.
The endpoint will look like /users?Id=1&id=2...
In Java, you can catch the query Params as below.
@QueryParam("id") List< Integer > ids
Upvotes: 1