Sub topic 9
Writing the REST controller
This chapter assumes you have the BookService, BookRequest, and BookResponse types from the earlier chapters, and that you know basic HTTP methods and Spring annotations. The controller is the web layer of the application. It receives HTTP requests, hands the work to the service, and turns the result into an HTTP response.
What a controller should do
A controller should stay thin. It does three things:
- It maps a URL and HTTP method to a Java method.
- It converts the request into Java values: path variables, query parameters, and a JSON body.
- It converts the service result into a response with the right status code.
Business rules and database access belong in the service and repository. This keeps the controller easy to read and easy to test in isolation.
The controller class
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public Page<BookResponse> list(Pageable pageable) {
return service.list(pageable);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable Long id) {
return service.get(id);
}
@PostMapping
public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request) {
BookResponse created = service.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(created.id())
.toUri();
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
public BookResponse update(@PathVariable Long id, @Valid @RequestBody BookRequest request) {
return service.update(id, request);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
service.delete(id);
}
}How the annotations work
@RestController combines @Controller and @ResponseBody. Return values are written straight to the response body, and Jackson serializes them to JSON. Without it, Spring would try to resolve a view template.
@RequestMapping("/api/books") sets a path prefix for every method in the class. The method-level annotations (@GetMapping, @PostMapping, @PutMapping, @DeleteMapping) add the HTTP method and any extra path.
The parameter annotations bind request data:
| Annotation | Source | Example |
|---|---|---|
| `@PathVariable` | A segment of the URL path | `/api/books/7` gives `id = 7` |
| `@RequestBody` | The JSON body, deserialized into a Java object | `{"title":"...","author":"..."}` |
| `Pageable` (no annotation) | The `page`, `size`, and `sort` query parameters | `?page=0&size=10` |
@Valid makes Spring check the validation annotations on BookRequest before the method runs. If the check fails, the method never executes and Spring answers with 400 Bad Request.
Status codes and constructor injection
Most methods return the DTO directly, and Spring sends 200 OK. Two methods differ:
createreturnsResponseEntityso it can set 201 Created and aLocationheader. The header points to the new resource, built from the current request URL plus the new id.deletereturns nothing and uses@ResponseStatusto send 204 No Content.
The controller receives BookService through its constructor. The field is final, so it cannot be null after construction. Spring injects the dependency automatically, because the class has a single constructor.
Common errors
- Using
@Controllerinstead of@RestController. Responses fail with a missing view error instead of returning JSON. - Leaving out
@RequestBody. The parameter is not bound from the JSON, so you get an object with null fields or a failure. - Returning the entity. This couples your JSON to your table. Return the response record instead.
- Putting logic in the controller. Rules written here are hard to reuse and hard to test.
Exercise
A client sends POST /api/books with a valid body, and the response is 200 OK with no Location header. Which part of create would you check, and what should it return?
Show answer
Check that the method returns ResponseEntity.created(location).body(created) instead of the plain DTO. Returning the DTO gives 200 OK. ResponseEntity.created sets 201 Created and the Location header.