Search⌘ K

@PathVariable

Explore how to create REST API endpoints in Spring that accept path variables for dynamic data retrieval. Learn to use the @PathVariable annotation to bind URL parameters to controller methods, handle Optional returns from JpaRepository's findById, and manage errors for missing data. Understand testing these endpoints with tools like Postman to ensure proper response handling.

In this lesson we will create a new endpoint for our REST API to retrieve a single player based on the id field. We will fetch the required player from the Player table.

Path variables

Path variables are a way of parameterizing the path or endpoint to accept data. Path variables are written in curly braces. When the client sends a request, it passes a value in place of the path variable. For example, we could say /players/1 to give us the player with Id 1, or /players/3 for the player with Id 3.

Path variable
Path variable

The REST client will send a request to /players/{playerId}, where playerId is a path variable. So the actual call may be /players/2. The REST service will return the player with id 2 from the Player table, which is Monfils.

GET request to /players/2
GET request to /players/2

JpaRepository interface provides us with methods for all basic CRUD ...