liveBook · Manning

@pathvariable

As explained in Spring in Action, Sixth Edition

@PathVariable is a Spring MVC annotation that binds a controller method parameter to a variable in the request path.

@PathVariable binds a controller method parameter to a variable embedded in the request path. For a controller rooted at /api/tacos, the route /api/tacos/{id} captures the actual path value and supplies it to the id parameter. section 7.1.1

Fetch a taco by ID

@GetMapping("/{id}") public ResponseEntity<Taco> tacoById(@PathVariable("id") Long id) { Optional<Taco> optTaco = tacoRepo.findById(id); if (optTaco.isPresent()) { return new ResponseEntity<>(optTaco.get(), HttpStatus.OK); } return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } A request to GET /api/tacos/4 passes 4 to id, which the repository uses to find the Taco. ResponseEntity lets the endpoint return 200 when found and 404 when no matching taco exists. section 7.1.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains placeholder mapping and repository use, then addresses missing resources with ResponseEntity and HTTP 404.
Examples
Uses GET /api/tacos/{id} to retrieve individual Taco objects by numeric ID.
What it assumes
Assumes familiarity with controller request mappings and repositories while demonstrating path binding through a taco API.
What you can do after
Build it from scratch by mapping a path identifier to repository-backed controller logic.
How it connects
Connects controller routing, REST APIs, repository lookup, Optional, ResponseEntity, and HTTP status codes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.