Overview
In this post, we will learn the different between @PathVariable and @RequestParam.
These both can be used to send the value from client to server, especially in REST API call.
@PathVariable
This parameter should be bound with the API URL. Let’s say, we want to fetch the particular user’s detail then we can create an API URL like:
example.com/users/101
And the code would look like following:
@GetMapping("/users/{id}") @ResponseStatus(code = HttpStatus.OK) public UserResponse getUser(@PathVariable Long id) { // Impl logic }
Hence, when we have to bind our request parameter value with the URL itself then we can use the PathVariable like the above example.
Note: we have to make sure that variable name on the method and the value for path {id}
should be same. Otherwise, spring does not bind the path value with the parameter in the method.
If you want to set a different path value and the method parameter then you have to define the path name explicitly so that it can be bind with the parameter.
@GetMapping("/users/{userId}") @ResponseStatus(code = HttpStatus.OK) public UserResponse getUser(@PathVariable("userId") Long id) { // here I have given the name of the path userId so that it will bind with the variable id // Impl logic }
@RequestParam
We can use this annotation to send the value in the query parameter of the web request. let’s take the following example:
example.com/users?status=active
Let’s implement it in the code.
@GetMapping("/users") @ResponseStatus(code = HttpStatus.OK) public UserResponse getUser(@RequestParam String status) { // Impl logic }
On the above example code, we haven’t added any value after /users in the @GetMapping annotation. So, spring will automatically binds the status=active sent in the URL with the variable status in getUser method.
Bonus tip
I usually prefer to use @RequestParam if there is an optional parameter to accept from the client. Otherwise, I will use the @PathVariable.
Conculsion
In this post, we learn the different between @PathVariable and @RequestParam.
We also learn, how to use them correctly.
Leave a Reply