Building Your First REST Controller
Building Your First REST Controller
Controllers are the front door of a Spring web application: they receive HTTP requests, delegate work, and return responses. With @RestController you mark a class as a web controller whose return values are written directly to the HTTP response body, typically as JSON.
Annotations at a glance
@RestController is a convenience that combines @Controller with @ResponseBody. Class-level or method-level mappings attach URLs to handler methods. Common ones are @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping, which match the corresponding HTTP methods.
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) {
this.service = service;
}
@GetMapping
public List<Product> allProducts() {
return service.findAll();
}
}
What makes it RESTful
RESTful design uses resources and HTTP verbs: GET retrieves, POST creates, PUT replaces, DELETE removes. Paths name nouns (like /api/products), not actions. The client and server negotiate with JSON bodies and status codes rather than action URLs.
Return values
Returning a plain object or list lets Jackson convert it to JSON automatically. Returning ResponseEntity gives you control over the HTTP status, headers, and body together, which is handy for created-resource responses and error payloads.
Controllers stay thin
Move business logic into service beans and persistence into repositories. A controller should map requests to service calls and translate results into responses. This keeps each layer focused and testable in isolation.
Key Points
@RestControllerwrites return values directly to the response body.- Use
@GetMapping,@PostMapping, and friends for HTTP-verb routing. - Class-level
@RequestMappinggroups endpoints under a common path. - Return JSON objects, lists, or
ResponseEntityfor full control. - Keep controllers thin and delegate to services.