Controllers and REST
In Spring MVC, a controller class handles HTTP requests. With @RestController, whatever a method returns is turned into the response body, usually as JSON. This lesson builds a REST API for products: path variables, query parameters, request bodies, status codes and headers.
Mapping requests
@RestController
public class GreetingController {
record Greeting(String language, String greeting) {}
@GetMapping("/greetings/{language}")
public Greeting greet(@PathVariable String language) {
String text = switch (language) {
case "en" -> "Hello";
case "hi" -> "Namaste";
case "es" -> "Hola";
default -> "👋";
};
return new Greeting(language, text);
}
}curl localhost:8080/greetings/hi{"language":"hi","greeting":"Namaste"}Returning a Java record is the cleanest way to shape JSON: Jackson writes one property per record component, in order.
| Annotation | Maps |
|---|---|
@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping |
One HTTP method + path |
@RequestMapping("/api/products") on the class |
A prefix for all methods in the controller |
@PathVariable |
A {placeholder} in the path |
@RequestParam |
A query parameter (required = false or defaultValue = "…" to make it optional) |
@RequestBody |
The JSON body, converted into an object |
@RequestHeader |
A header value |
A product API
Here's the API this track builds on. It has three layers:
ProductController → ProductService → ProductRepository → database
(HTTP) (business logic) (data access)The request and response shapes are records, kept separate from the database entity:
public record ProductRequest(String name, BigDecimal price, int stock, String category) {}
public record ProductResponse(Long id, String name, BigDecimal price, int stock, String category, boolean inStock) {
static ProductResponse from(Product p) {
return new ProductResponse(p.getId(), p.getName(), p.getPrice(), p.getStock(), p.getCategory(), p.getStock() > 0);
}
}And the controller:
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService service;
public ProductController(ProductService service) { // injected by Spring
this.service = service;
}
@GetMapping
public List<ProductResponse> list(@RequestParam(required = false) String category) {
return service.findAll(category).stream().map(ProductResponse::from).toList();
}
@GetMapping("/{id}")
public ProductResponse get(@PathVariable Long id) {
return ProductResponse.from(service.findById(id));
}
@PostMapping
public ResponseEntity<ProductResponse> create(@RequestBody ProductRequest request) {
Product saved = service.create(request);
return ResponseEntity.created(URI.create("/api/products/" + saved.getId())) // 201 + Location
.body(ProductResponse.from(saved));
}
@PutMapping("/{id}")
public ProductResponse update(@PathVariable Long id, @RequestBody ProductRequest request) {
return ProductResponse.from(service.update(id, request));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build(); // 204
}
}Trying it with curl
curl localhost:8080/api/products
curl "localhost:8080/api/products?category=kitchen"
curl localhost:8080/api/products/2[{"id":1,"name":"Laptop","price":899.00,"stock":15,"category":"electronics","inStock":true},{"id":2,"name":"Mug","price":8.99,"stock":200,"category":"kitchen","inStock":true},{"id":3,"name":"Teapot","price":34.50,"stock":0,"category":"kitchen","inStock":false}]
[{"id":2,"name":"Mug","price":8.99,"stock":200,"category":"kitchen","inStock":true},{"id":3,"name":"Teapot","price":34.50,"stock":0,"category":"kitchen","inStock":false}]
{"id":2,"name":"Mug","price":8.99,"stock":200,"category":"kitchen","inStock":true}Creating a product (-i shows the status line and headers):
curl -i -X POST localhost:8080/api/products \
-H "Content-Type: application/json" \
-d '{"name":"Lamp","price":29.00,"stock":4,"category":"home"}'HTTP/1.1 201
Location: /api/products/4
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 20 Nov 2026 17:24:36 GMT
{"id":4,"name":"Lamp","price":29.00,"stock":4,"category":"home","inStock":true}Updating and deleting:
curl -X PUT localhost:8080/api/products/3 -H "Content-Type: application/json" \
-d '{"name":"Teapot","price":32.00,"stock":12,"category":"kitchen"}'
curl -i -X DELETE localhost:8080/api/products/1{"id":3,"name":"Teapot","price":32.00,"stock":12,"category":"kitchen","inStock":true}
HTTP/1.1 204
Date: Fri, 20 Nov 2026 17:24:36 GMTResponseEntity
Return a plain object for a normal 200 OK. Return ResponseEntity when you need to control the status or headers:
return ResponseEntity.ok(body); // 200
return ResponseEntity.created(location).body(body); // 201 + Location
return ResponseEntity.noContent().build(); // 204
return ResponseEntity.status(HttpStatus.CONFLICT).body(err); // any status
return ResponseEntity.ok().header("Cache-Control", "max-age=60").body(body);What Spring does when things go wrong
Without any extra code, Spring Boot already answers sensibly. Unknown URLs and unreadable JSON get a JSON error:
curl localhost:8080/nope
curl -X POST localhost:8080/api/products -H "Content-Type: application/json" -d '{bad'{"timestamp":"2026-11-20T17:24:36.174Z","status":404,"error":"Not Found","path":"/nope"}
{"timestamp":"2026-11-20T17:24:36.161Z","status":400,"error":"Bad Request","path":"/api/products"}The Validation and error handling lesson replaces these with consistent, informative Problem Details responses.
Why DTOs instead of entities?
It's tempting to return the JPA Product entity directly. Don't:
- The API would change every time the database schema changes.
- Clients could set fields they shouldn't (an
id, acreatedBy) through@RequestBody. - Lazy-loaded relationships cause errors or huge responses during JSON conversion.
Records make separate request and response types (DTOs, data transfer objects) almost free.
Practice
- Add
GET /api/products/search?q=mugthat finds products whose name containsq. - Make
POSTreturn409 Conflictwhen a product with the same name already exists. - Add a
@RequestHeader("X-Request-Id")parameter (optional) and log it.
1.What does @RestController do?
2.How do you return 201 Created with a Location header?
3.Why use a separate record (DTO) instead of returning the JPA entity?