Card 01/ 06

ConceptDifficulty: Intermediate1 min

Request Mapping Annotations: One per HTTP Verb

@GetMapping, @PostMapping, @PutMapping and @DeleteMapping each name the verb and the path a method answers.

A REST controller is a class whose methods answer HTTP requests, and each method needs a mapping: which HTTP verb (the kind of request, such as GET or POST) and which path it answers. Spring has one annotation per common verb, and @GetMapping("/rides/{id}") states both the verb and the path in one line.

A ride-sharing API needs to fetch a ride, create one, replace one and cancel one. Those are four different verbs on the same kind of path, and each becomes one annotated method.

The mapping annotations and the verbs they answer
AnnotationVerbUsual meaning
@GetMappingGETRead, with no side effect
@PostMappingPOSTCreate
@PutMappingPUTReplace
@DeleteMappingDELETERemove

All four are shortcuts for the general @RequestMapping, which takes the verb as an argument: @RequestMapping(value = "/rides/{id}", method = RequestMethod.GET) means the same as @GetMapping("/rides/{id}"). The shortcuts exist so that the verb is visible at a glance, and @PatchMapping, for partial updates, completes the set.

{id} in a path is a path variable: a placeholder that matches any value in that position, so /rides/42 and /rides/ride-7 both reach the same method.

So a controller reads like a table of the API: each method's annotation says which request it answers. Two methods that claim the same verb and path stop the application from starting, with an error about an ambiguous mapping.