git change remote url

Difference between @PathVariable and @RequestParam


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.


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:

And the code would look like the following:

@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.

@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


We can use this annotation to send the value in the query parameter of the web request. let’s take the following example:

Let’s implement it in the code.

@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.


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

We also learn, how to use them correctly.

Notify of
Inline Feedbacks
View all comments