Spring Boot 3.1 RESTController @GetMapping with PathVariable: Dynamic API Routing
In Spring Boot 3.1, you can define GET requests for RESTful APIs using the @GetMapping annotation within methods annotated with @RestController. To include dynamic parameters in the API path, leverage the @PathVariable annotation.
For instance, consider a user management API that retrieves user information based on their ID. You can define a @RestController method like this:
@RestController
public class UserController {
@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
// Retrieve user information based on userId
User user = userService.getUserById(userId);
return user;
}
}
In this code, @GetMapping specifies the GET request, while @PathVariable extracts the dynamic userId parameter from the URL path.
When a client sends a request, they can replace userId in the path with the specific ID. For example:
GET /users/123
This request will retrieve user information for the ID 123.
Crucially, the value of the @PathVariable annotation must match the parameter name in the path. In our example, we use @PathVariable Long userId to extract userId. If the path parameter name differs, adjust the @PathVariable annotation accordingly.
原文地址: https://www.cveoy.top/t/topic/ovOB 著作权归作者所有。请勿转载和采集!