git change remote url

Difference between @PathVariable and @RequestParam

Overview

In this post, we will learn the difference 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 the 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 the variable name on the method and the value for the path {id} should be the same. Otherwise, the 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 bound 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
}

In the above example code, we haven’t added any value after /users in the @GetMapping annotation. So, spring will automatically bind 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.

Conclusion

In this post, we learn the difference between @PathVariable and @RequestParam.

We also learn, how to use them correctly.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments