PathVariable vs RequestParam in Spring Boot: When to use them
In Spring Boot, annotations like @PathVariable and @RequestParam are used to handle HTTP request data in different ways
The similarities between them are
The difference between them is what we are going to explore and understand in this article.
@PathVariable Annotation
if you have a url like this - http://example.com/posts - for creating a post
you simply write a method in the Controller like so
In a real word app, you would definitely want to be able to get a post by passing the 'id' somewhere and, that is where a @PathVariable is useful.
to get a particular post by passing the 'id', you would want the url to look like this - http://example.com/posts/1 - and this translates to us writing the Controller method this way.
the 'id' parameter in the getPostById method must also match the parameter in the @GetMapping annotation.
If you want it to have a different name, @PathVariable has a property called 'name' and the method ends up looking like this
There is another property called 'required' that has a default value of true, if the client calling the endpoint does not pass the 'id' in the url, an exception is thrown.
Recommended by LinkedIn
@RequestParam Annotation
@RequestParam is mostly used when there is an endpoint you can query for data, like searching for a particular data according to some attributes.
For example, if we want to create an endpoint where a client can search for a post/posts by passing the Post’s tag and number of likes, the controller method will be written this way
and the url will look this way http://example.com/posts?tag=cooking&likes=50
Depending on your design, this endpoint could mean - get the list of posts where the tag equals cooking and it has at least 50 likes
You can have as many @RequestParam as you want, and also note that any or all of them can be optional.
Notice that the question mark makes the difference between a URL that just needs a @PathVariable and another that needs a @RequestParam.
Another thing to note is this - @RequestParam does not need you passing the 'tag' parameter in the @GetMapping annotation.
@RequestParam also has a 'name' and 'required' property like @PathVariable.
@RequestParam has a 'defaultValue' property for when the parameter is not provided when the endpoint is called.
In summary,
@PathVariable is used when the URL structure defines variables, such as resource identifiers in a RESTful API.
@RequestParam is used for optional or required query parameters in an http request.