Sub topic 9
Writing the REST controller
The controller is the outermost layer of the API. It receives an HTTP request, hands the work to the service, and turns the result into an HTTP response. This chapter covers how Spring maps requests to methods, how arguments are bound, and what the controller should and should not do.
Prerequisites
This chapter assumes you know the following:
- Java classes, records, and annotations.
- HTTP methods, status codes, and JSON.
- The
BookService,BookRequest, andBookResponsetypes from the earlier chapters.
The chapter shows the full controller and then explains each part. The status codes for each endpoint and the validation rules are covered in more detail in the next chapters.
Where the controller sits
A request passes through several layers. The controller is the only one that knows about HTTP. The service and repository work with plain Java objects.
Keeping HTTP concerns in one layer has a practical payoff. You can change a URL or a status code without touching business logic, and you can test the service without starting a web server.
The complete controller
@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);
}
}The class needs these imports to compile:
import java.net.URI;
import jakarta.validation.Valid;
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;Class-level annotations
@RestController
@RestController combines @Controller and @ResponseBody. Spring registers the class as a bean and treats every return value as the response body, not as the name of a view. A BookResponse returned from a method is converted to JSON by Jackson, the JSON library that Spring Boot includes with spring-boot-starter-web.
@RequestMapping
A class-level @RequestMapping("/api/books") sets a path prefix for every method in the class. Each method then adds its own suffix. This removes repetition and keeps all routes for one resource in one place.
The /api prefix is a convention. It separates API routes from any static pages the same application might serve.
Mapping methods to HTTP operations
Each method annotation is a shortcut for @RequestMapping with a fixed HTTP method.
| Annotation | HTTP method | Path | Typical use |
|---|---|---|---|
| `@GetMapping` | GET | `/api/books` | List books |
| `@GetMapping("/{id}")` | GET | `/api/books/{id}` | Read one book |
| `@PostMapping` | POST | `/api/books` | Create a book |
| `@PutMapping("/{id}")` | PUT | `/api/books/{id}` | Replace a book |
| `@DeleteMapping("/{id}")` | DELETE | `/api/books/{id}` | Delete a book |
Spring matches on both path and method. A DELETE request to /api/books has no matching handler, so Spring answers with 405 Method Not Allowed and an Allow header that lists the methods the path does support.
Binding request data to arguments
Spring inspects each parameter and decides where its value comes from.
Path variables
@PathVariable Long id takes the {id} segment from the URL and converts it to a Long. If a client calls /api/books/abc, the conversion fails and Spring returns 400 Bad Request with a MethodArgumentTypeMismatchException behind it. You do not write any code for that case.
When the parameter name matches the placeholder name, you can omit the name in the annotation. This works because Spring Boot's Maven and Gradle plugins compile with the -parameters flag. If you build with a plain javac setup, write @PathVariable("id") to be safe.
Request bodies
@RequestBody BookRequest request tells Spring to read the request body and deserialize the JSON into a BookRequest. Three failures are worth knowing:
- Malformed JSON gives
400 Bad Request. - A missing or wrong
Content-Typeheader gives415 Unsupported Media Type. Clients must sendContent-Type: application/json. - An empty body gives
400 Bad Request, because@RequestBodyis required by default.
Jackson can deserialize records, so BookRequest needs no setters or annotations beyond the validation constraints.
The @Valid annotation
@Valid makes Spring run Bean Validation on the deserialized object before the method body executes. If a constraint such as @NotBlank fails, the method never runs. Spring throws MethodArgumentNotValidException, which it maps to 400 Bad Request by default. The validation chapter covers the details.
Pageable
Pageable is a Spring Data type. Spring MVC builds it from the page, size, and sort query parameters. A request such as GET /api/books?page=0&size=10&sort=title,asc becomes a Pageable for the first page of ten books, sorted by title. If the client sends no parameters, Spring uses page 0 and size 20.
Building responses
Returning the object directly
Methods such as get and update return BookResponse. Spring writes it as JSON with status 200 OK. This is the simplest form and fits when the status is always the default.
Using ResponseEntity
ResponseEntity<T> lets you control the status, the headers, and the body. The create method needs it because it sets two things the default does not:
- The status is
201 Created, not200 OK. - A
Locationheader holds the URL of the new resource.
ServletUriComponentsBuilder.fromCurrentRequest() starts from the URL of the current request, /api/books. The code appends /{id}, fills in the new id, and produces http://localhost:8080/api/books/42. Building the URL from the request avoids hard-coding the host, port, or context path. It also keeps working behind a proxy that Spring is configured to trust for forwarded headers.
Using @ResponseStatus
The delete method returns void. Without further instruction, Spring would answer 200 OK with an empty body. @ResponseStatus(HttpStatus.NO_CONTENT) changes that to 204 No Content, which is the accurate answer when there is nothing to send back.
The two techniques solve different problems:
| Technique | Use when | Limitation |
|---|---|---|
| Return the object | The status is always `200 OK` | Cannot set headers or vary the status |
| `@ResponseStatus` | The status is fixed but not 200 | Cannot set headers or vary the status |
| `ResponseEntity` | You need headers or a status that depends on logic | More code per method |
What belongs in the controller
A controller method should do four things: receive input, trigger validation, call one service method, and shape the response. Anything else usually belongs elsewhere.
- Business rules, such as "a title must be unique", go in the service.
- Queries and persistence go in the repository.
- Entity-to-DTO conversion happens in the service in this tutorial, so the controller never touches an entity.
- Translating exceptions to HTTP errors goes in a
@RestControllerAdviceclass, so no controller needs a try/catch block.
This is why get is one line long. If the book is missing, the service throws BookNotFoundException and the exception handler produces the 404. The controller does not check for null or inspect an Optional.
Constructor injection
The controller declares BookService as a final field and receives it through the constructor. When a class has a single constructor, Spring uses it without @Autowired. This style has three benefits:
- The field can be
final, so the dependency cannot change after construction. - A test can build the controller with
new BookController(mockService)and no Spring context. - A missing dependency fails at startup, not on the first request.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `404` on every request | Wrong path, or the class is outside the package of the main application class and component scanning misses it | Check `@RequestMapping` and move the class under the main package |
| `415 Unsupported Media Type` on POST | Client did not send `Content-Type: application/json` | Add the header to the request |
| `405 Method Not Allowed` | The path exists, but not for this HTTP method | Compare the client method with the mapping |
| `400` with a conversion error | The path id is not a number | Fix the client, or accept the `400` as correct |
| Response shows an empty `{}` or a serialization error | The returned type has no getters | Return a record or a class with accessors |
| Validation never runs | `@Valid` is missing, or `spring-boot-starter-validation` is not on the classpath | Add the annotation and the starter |
| `Location` header points to the wrong host | A proxy hides the original host | Set `server.forward-headers-strategy=framework` |
PUT and the contract it implies
The update method replaces the whole resource. BookRequest requires both title and author, so a client must send both. That matches the meaning of PUT: the request body is the new state of the resource. If you later want to change one field at a time, add a PATCH endpoint with its own request type where fields are optional. Do not loosen the PUT rules to get that behavior.
PUT is also idempotent. Sending the same request twice leaves the resource in the same state as sending it once. POST is not idempotent: sending the same create request twice makes two books.
Trying the controller
With the application running on port 8080, these curl commands exercise each route:
curl -i -X POST http://localhost:8080/api/books \
-H "Content-Type: application/json" \
-d '{"title":"Refactoring","author":"Martin Fowler"}'
curl -i http://localhost:8080/api/books/1
curl -i "http://localhost:8080/api/books?page=0&size=5&sort=title,asc"
curl -i -X PUT http://localhost:8080/api/books/1 \
-H "Content-Type: application/json" \
-d '{"title":"Refactoring, 2nd edition","author":"Martin Fowler"}'
curl -i -X DELETE http://localhost:8080/api/books/1The first call should return 201 Created and a Location: http://localhost:8080/api/books/1 header. The last should return 204 No Content. Calling the GET on id 1 again after the delete returns 404 once the exception handler from a later chapter is in place.
Summary of the design
@RestControllerplus@RequestMappingdefines the resource root.- Method-level annotations pick the HTTP method and the path suffix.
- Spring binds path, body, and query data to typed parameters.
ResponseEntityand@ResponseStatusset non-default status codes and headers.- The controller stays thin. The service holds the logic, and the advice class holds the error mapping.
Exercise
A client sends POST /api/books with a valid JSON body but forgets the Content-Type header. Which status code does Spring return, and which part of the controller would you change if you wanted the response for a successful create to be 200 OK without a Location header?
Show answer
Spring returns 415 Unsupported Media Type, because it cannot choose a message converter for the body. To return 200 OK without a Location header, change the create method to return BookResponse directly, as get does, and drop the ResponseEntity and the URI-building code.
Exercise
Why does the delete method use @ResponseStatus(HttpStatus.NO_CONTENT) while the create method returns a ResponseEntity?
Show answer
The delete method always returns the same fixed status and has no headers or body to set, so the annotation is enough. The create method must add a Location header in addition to the 201 status, and only ResponseEntity can set headers.
Exercise
A request to GET /api/books/abc returns 400 even though you wrote no code to check the id. Explain where the 400 comes from.
Show answer
The @PathVariable Long id parameter requires Spring to convert the string "abc" to a Long. The conversion fails and Spring raises MethodArgumentTypeMismatchException, which its default error handling maps to 400 Bad Request.