Context:
I want to write an endpoint that will return a Collection
of users based on their usernames. How should those username be passed to the REST endpoint - note that I can (potentially) have a lot of usernames (say > 5000)?
Solution #1:
Use a GET
endpoint, concatenate the usernames on client side and pass them as a single request parameter. Split the request parameter on server side to get the list of usernames.
@RestController
public class UserController {
@GetMapping
// able to deserialize `filename1,filename2` to List out of the box
public Collection<User> getUser(@RequestParam List<String> usernames) {
return userService.getUsersByUsername(usernames);
}
}
Solution #2:
Use a POST
endpoint and pass the list of usernames as request body. Although cleaner form a coding perspective, I end up using a POST
to fetch data.
@RestController
public class UserController {
@PostMapping
public Collection<User> getUser(@RequestBody List<String> usernames) {
return userService.getUsersByUsername(usernames);
}
}
Questions:
- Which of the two solutions would be the better approach?
- Do you have a better approach to pass the list of usernames into the endpoint?
Edits:
- I've updated the signature of the first solution based on suggestions from answers. Spring is able to deserialize
filename1,filename2
to List out of the box for@RequestParam
.