Building REST APIs in Spring Boot relies on a small set of core annotations that define controllers, map HTTP requests, and bind request data to method parameters.
Key Points: • @RestController marks a class as a REST controller, combining @Controller and @ResponseBody so every method's return value is serialized straight into the response body. • @RequestMapping maps a base path or specific HTTP method to handler methods, and is the general-purpose mapping annotation. • @GetMapping and @PostMapping are shorthand for @RequestMapping restricted to GET and POST respectively, with @PutMapping and @DeleteMapping following the same pattern. • @PathVariable binds a value from the URI template, like an ID, directly to a method parameter. • @RequestBody deserializes the incoming JSON request body into a Java object for POST and PUT handlers.
Example: A ProductController annotated with @RestController exposes GET /products/{id} using @GetMapping and @PathVariable to fetch a single product, and POST /products using @PostMapping and @RequestBody to create one from a JSON payload.
Code Example:
@RestController
@RequestMapping("/products")
public class ProductController {
@GetMapping("/{id}")
public Product getProduct(@PathVariable Long id) {
return productService.findById(id);
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.save(product);
}
}Interview Tip: A concise interview answer is:
"The core ones I reach for are @RestController to mark the class, @RequestMapping or its shortcuts like @GetMapping and @PostMapping to map HTTP requests, @PathVariable to bind URI segments, and @RequestBody to deserialize the JSON payload into a Java object. Together they cover most of what a typical REST endpoint needs."