Sub topic 3
Your First @RestController
This chapter covers how a Spring Boot application turns an HTTP request into a Java method call. It builds a small BookController and explains the annotations, the request flow, and the errors you are most likely to meet.
It assumes you know Java classes, interfaces and records, basic HTTP (methods, status codes, headers), and Maven or Gradle. It also assumes you have a Spring Boot project with the spring-boot-starter-web dependency, and that you know the basic idea of dependency injection. The chapters on request body binding, validation and error handling build on this one, so we keep the scope narrow here.
What a @RestController is
A @RestController is a Spring component whose methods handle web requests and write their return values directly into the HTTP response body. It combines two annotations:
@Controllermarks the class as a web component. Component scanning finds it and registers it as a bean.@ResponseBodytells Spring MVC to serialize the return value, usually to JSON, instead of treating it as the name of a view template.
Without @ResponseBody, a method that returns a String such as "books" would make Spring look for a template called books. With @RestController, the string itself becomes the response body.
The request flow
Spring MVC is built around a single front controller called the DispatcherServlet. Every request passes through it. It asks a handler mapping which controller method matches the request, calls that method with the arguments it resolved from the request, and then writes the result with an HTTP message converter.
Two parts of this flow matter for the rest of the chapter. Argument resolvers build the method arguments from the URL, query string and body. Message converters turn the returned object into bytes. In a standard Boot web project, Jackson does the JSON conversion.
A complete controller
Here is the controller from this tutorial's running example. It uses a class-level base path, constructor injection, a query parameter with a default, and a path variable.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public List<BookResponse> list(@RequestParam(defaultValue = "") String title) {
return service.search(title);
}
@GetMapping("/{id}")
public BookResponse get(@PathVariable long id) {
return service.get(id);
}
}The class needs a BookService and a BookResponse to compile. Later chapters cover them properly. For now, this minimal version is enough to run the controller:
public record BookResponse(long id, String title, String author) {}
@Service
public class BookService {
private final List<BookResponse> books = List.of(
new BookResponse(1, "Dune", "Frank Herbert"),
new BookResponse(2, "Emma", "Jane Austen"));
public List<BookResponse> search(String title) {
return books.stream()
.filter(b -> b.title().toLowerCase().contains(title.toLowerCase()))
.toList();
}
public BookResponse get(long id) {
return books.stream()
.filter(b -> b.id() == id)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No book with id " + id));
}
}Start the application and call it:
curl -i http://localhost:8080/api/books/1You should see HTTP/1.1 200 and a body of {"id":1,"title":"Dune","author":"Frank Herbert"}. The Content-Type header is application/json.
Reading it line by line
@RequestMapping("/api/books")on the class sets a prefix. Every method mapping inside the class is appended to it.- The constructor takes a
BookService. Spring sees a single constructor and injects the bean, so no@Autowiredis needed. Afinalfield keeps the dependency immutable and makes the class easy to construct in a plain unit test. @GetMappingwith no path mapsGET /api/books.@GetMapping("/{id}")mapsGET /api/books/{id}. The{id}segment is a URI template variable.@RequestParam(defaultValue = "")reads?title=.... If the parameter is missing, Spring uses an empty string, andcontains("")is true for every title, so the list returns everything.@PathVariable long idbinds the{id}segment and converts the text to along.
Methods return plain objects. Spring picks status 200 OK and serializes the object. The chapter on ResponseEntity shows how to take control of that.
Request mapping basics
@GetMapping is a shortcut for @RequestMapping(method = RequestMethod.GET). The same pattern exists for the other verbs: @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping. The next chapter covers them in detail.
Spring combines the class-level and method-level paths. It matches on the HTTP method as well as the path, so GET /api/books and POST /api/books can go to different methods.
| Request | Matched method |
|---|---|
| `GET /api/books` | `list` |
| `GET /api/books?title=du` | `list`, with `title` set to `du` |
| `GET /api/books/1` | `get`, with `id` set to `1` |
| `POST /api/books` | none, so Spring returns `405 Method Not Allowed` |
The 405 response in the last row is useful when you debug. It means the path exists but no method accepts that HTTP verb.
Common errors
Most first-controller problems fall into a few categories. Knowing the symptom saves time.
| Symptom | Likely cause |
|---|---|
| `404` for every URL, and the controller is not listed in the startup logs | The class is outside the package of the `@SpringBootApplication` class, so component scanning misses it |
| Response body is the plain text of a class name or a view lookup error | `@Controller` was used instead of `@RestController`, so there is no `@ResponseBody` |
| `406 Not Acceptable` or a message converter error | No Jackson on the classpath, or the object cannot be serialized |
| `400 Bad Request` on `/api/books/abc` | The path variable cannot be converted to `long` |
| `400 Bad Request` with a missing parameter message | A `@RequestParam` without a default value is required by default |
| `405 Method Not Allowed` | The path matches but the HTTP method does not |
| `NoSuchBeanDefinitionException` for `BookService` at startup | The service class lacks `@Service` or is outside the scanned packages |
Parameter names
@PathVariable long id and @RequestParam String title rely on parameter names. Spring Boot's Maven and Gradle plugins compile with -parameters, so this works by default. If you compile with a custom setup that omits that flag, you get an error about a missing name. The safe fix is to enable the flag. Writing the name explicitly, for example @PathVariable("id") long id, also works.
Required versus optional
A @RequestParam is required unless you give it a defaultValue, set required = false, or declare it as Optional<String>. A @PathVariable is always required, because the path would not match without it.
@GetMapping("/search")
public List<BookResponse> search(@RequestParam Optional<String> author) {
return author.map(service::byAuthor).orElseGet(service::all);
}That example assumes BookService has byAuthor and all methods. It shows the Optional form only. The simple controller above does not need it.
Design rules for a first controller
Keep these habits from the start, since they make later chapters easier:
- Put the shared path prefix on the class with
@RequestMapping, and keep method paths short. - Use constructor injection with
finalfields. - Return DTOs such as
BookResponse, not internal entities. This keeps your public JSON contract separate from your storage model. - Keep the method body to one or two lines. The controller translates between HTTP and Java, and the service holds the business logic.
- Version or namespace your API under a prefix like
/apiso you can add routes later without conflicts.
Checking your understanding
Exercise
A teammate writes @Controller on a class and returns a BookResponse from a method annotated with @GetMapping("/{id}"). The request fails with an error about a missing view or template. What is wrong, and what are two ways to fix it?
Show answer
@Controller does not include @ResponseBody, so Spring treats the return value as a view name instead of writing it as JSON. Fix it by replacing @Controller with @RestController, or by keeping @Controller and adding @ResponseBody to the class or method.
Exercise
Given the BookController above, what does GET /api/books return when called without a query string, and why? What status does DELETE /api/books/1 return?
Show answer
It returns all books with status 200. The title parameter is absent, so it takes the default value of an empty string, and every title contains the empty string. DELETE /api/books/1 returns 405 Method Not Allowed, because the path /api/books/{id} is mapped but only for GET.