@PathVariable Example in Spring Boot REST

This tutorial will teach you how to use a @PathVariable parameter to read the path parameter value. I will also include here a video tutorial so you can see how to do it on video.

To learn how to read request parameters from a query string, read the @RequestParam example tutorial.

Let’s say we have the following URL:

http://localhost:8080/api/users/5jg8hf4ys9fit

If we break the above URL down into smaller parts then we will see that:

  • HTTP – is the protocol being used,
  • localhost  – is the domain name,
  • 8080 – is the port number,
  • api – is the root path of your web services application,
  • users – is most likely the @Path value of your Root Resource class and,
  • 5jg8hf4ys9fit – is the path parameter value which we can read with @PathVariable annotation.

So how do we read the value of 5jg8hf4ys9fit from the URL path using the @PathVariable annotation?

@PathVariable. Reading URL Path Parameters

Here is an example of @RestController class that uses @GetMapping and @PathVariable annotation to handle HTTP Get request and read the value of path parameter from the URL mentioned above.

  • Use @GetMapping to define path value, like so:
    @GetMapping(path = "/{userId}")
  • Use @PathVariable to read the path parameter value and make it available as a method argument
    public UserRest getUser(@PathVariable String userId)

@RestController class example:

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    UserService userService;
 
    @GetMapping(path = "/{userId}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public UserRest getUser(@PathVariable String userId) {

        UserRest returnValue = new UserRest();

        UserDto userDto = userService.getUser(userId);
        BeanUtils.copyProperties(userDto, returnValue);

        return returnValue;
    }

}

Reading Multiple Path Variables

Sometimes URL to a web service endpoint might contain more than one path variable. Let’s, for example, assume you have the following URL:

http://localhost:8080/users/<userId>/messages/<messageId>

You can read the userId and the messageId path variables in the following way:

@GetMapping(path = "/{userId}/messages/{messageId}")
public String getUser(@PathVariable String userId, @PathVariable String messageId)
{
 return "get user was called with path userId variable " + userId + " and message id" + messageId;
}

Reading URL Parth Parameters Video Tutorial

I hope this example was helpful to you. Check out the below video courses if you are interested to learn more about the Spring Boot framework.


Leave a Reply

Your email address will not be published. Required fields are marked *