Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 66 ยท Building REST APIs

REST Controllers

Build REST endpoints in Spring Boot with @RestController, @GetMapping and friends, path variables, request params, status codes, ResponseEntity and content negotiation.

A REST controller is the front door of your application: it receives an HTTP request, calls your services and turns the result into an HTTP response. Spring MVC does the heavy lifting of routing, argument conversion and writing JSON, so a controller method is often just a few lines of plain Java with annotations that say "this method handles GET /api/books/{id}".

This lesson covers the building blocks you will use in nearly every API: @RestController, the mapping annotations, path variables and query parameters, status codes, ResponseEntity and content negotiation. For the general MVC model, see REST Controllers in Advanced Java; this lesson is the Spring Boot view of the same ideas.

Real Spring MVC cannot run in our sandbox, so controller code is shown read-only. The runnable stand-in is a mini MVC dispatcher that finds annotated methods by reflection, matches URLs, converts arguments and produces 404, 405 and 400 responses like the real thing.

Your first controller

Java
package com.shop.book;

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookService books;

    public BookController(BookService books) {
        this.books = books;
    }

    @GetMapping
    public List<Book> list() {
        return books.findAll();
    }

    @GetMapping("/{id}")
    public Book get(@PathVariable long id) {
        return books.findById(id);
    }
}

@RestController is shorthand for @Controller plus @ResponseBody: whatever a method returns is written to the response body (as JSON by default), not interpreted as the name of a view. @RequestMapping("/api/books") on the class gives all methods a common prefix. @GetMapping on a method means "handle GET requests", with an optional path added to the prefix.

The controller is a normal bean found by component scanning, and it receives its collaborators through the constructor, as you learned in IoC and Dependency Injection. Keep controllers thin: translate HTTP into method calls and back, and leave business rules to services.

One annotation per HTTP method

@GetMapping Read. Safe and cacheable.
@PostMapping Create. Not idempotent.
@PutMapping Replace a whole resource.
@PatchMapping Change some fields.

@DeleteMapping removes a resource; repeating it is safe.

1 / 2

Path variables and request parameters

A path variable identifies one resource: /api/books/42. A request parameter refines a request: /api/books?author=Le%20Guin&limit=5. Spring converts the text to the declared Java type for you.

Java
@GetMapping
public List<Book> search(
        @RequestParam(required = false) String author,
        @RequestParam(defaultValue = "10") int limit) {
    return books.search(author, limit);
}

@GetMapping("/{id}")
public Book get(@PathVariable long id) {
    return books.findById(id);
}

@GetMapping("/{id:\\d+}/reviews/{reviewId}")
public Review review(@PathVariable long id, @PathVariable long reviewId) {
    return books.review(id, reviewId);
}

Parameter names are inferred from the Java parameter names, which works because Boot's Maven and Gradle setups compile with -parameters. If your build does not, write the name out: @PathVariable("id"). A parameter without required = false or a default is mandatory, and a missing one produces 400 Bad Request. So does /api/books/abc when id is a long, because the conversion fails.

A regular expression after a colon ({id:\\d+}) restricts what a variable matches. Since Spring Framework 6, a trailing slash no longer matches by default: /api/books/ is not /api/books.

Status codes and ResponseEntity

Returning an object gives 200 OK. For anything else you have two options. @ResponseStatus fixes a status for a method, and ResponseEntity lets you decide at runtime and add headers.

Java
@PostMapping
public ResponseEntity<Book> create(@RequestBody NewBook request) {
    Book saved = books.create(request);
    URI location = URI.create("/api/books/" + saved.id());
    return ResponseEntity.created(location).body(saved);          // 201 + Location header
}

@GetMapping("/{id}")
public ResponseEntity<Book> find(@PathVariable long id) {
    return books.findOptional(id)
            .map(ResponseEntity::ok)                               // 200
            .orElseGet(() -> ResponseEntity.notFound().build());   // 404
}

@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)                             // 204, no body
public void delete(@PathVariable long id) {
    books.delete(id);
}

The codes you will use most often:

Code Meaning Typical use
200 OK Success with a body GET, PUT, PATCH
201 Created New resource, with Location POST that creates
204 No Content Success, nothing to return DELETE, some PUTs
400 Bad Request Malformed or invalid input Bad JSON, failed conversion
404 Not Found No such resource Unknown id or path
405 Method Not Allowed Path exists, wrong verb POST /api/books/42
406 Not Acceptable Cannot produce the requested type Odd Accept header
415 Unsupported Media Type Cannot read the body's type Wrong Content-Type
500 Internal Server Error Bug on the server Unhandled exception

Throwing an exception is often cleaner than building a ResponseEntity for errors. Lesson Error Handling and Problem Details shows how to turn exceptions into consistent responses.

Content negotiation

The client says what it can accept with the Accept header, and says what it is sending with Content-Type. Spring picks a converter for each. With Jackson on the classpath (the web starter adds it), JSON is the default for both directions. You can narrow a method:

Java
@PostMapping(consumes = "application/json", produces = "application/json")
public Book create(@RequestBody NewBook request) { /* ... */ }

A request with Content-Type: text/plain then gets 415, and Accept: application/xml gets 406. Declare produces and consumes when an endpoint is deliberately JSON-only; leave them out otherwise. How bodies are converted is the subject of Request and Response Bodies with Jackson.

How the dispatcher finds your method

All requests enter Spring MVC through one servlet, the DispatcherServlet. It asks the handler mappings which method matches the request, resolves each method argument, calls the method, and writes the return value using a message converter. That sequence is easy to model, and modeling it shows exactly why you get a 404 for an unknown path but a 405 for a known path with the wrong verb.

Java A mini MVC dispatcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is real: annotation-driven routing, converting path and query text to the parameter type, 404 for an unknown path but 405 (with an Allow header) for a known path with the wrong verb, 400 for a failed conversion, and 406 for an unsupported Accept. What is the stand-in: the real DispatcherServlet has pluggable handler mappings, many more argument resolvers, message converters (Jackson) for bodies and results, interceptors, exception resolvers and a full content negotiation strategy.

Good controller habits

  • Name resources with nouns and plurals: /api/books, not /api/getBooks. The HTTP verb is the action.
  • Return the right status. 201 plus Location for creation, 204 for delete, 404 for a missing resource, not 200 with an error message in the body.
  • Do not expose entities directly. Return small response records (DTOs) so your database model can change without breaking clients; see the next lesson.
  • Keep logic out. A controller method that is longer than about ten lines usually wants a service.
  • Avoid overloading one URL with many behaviors. If a method switches on a parameter to do different things, split it into separate endpoints.
  • Version deliberately. Decide on a versioning rule before the first client depends on your API (covered in Designing a Clean API).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @RestController add compared with @Controller?

    @RestController is @Controller plus @ResponseBody, so every handler method's return value becomes the response body.
  2. 2. A client sends POST /api/books/2, but only GET and DELETE are mapped for that path. What does Spring MVC return?

    The path exists, so it is not a 404; the verb is wrong, so Spring answers 405 and lists the allowed methods.
  3. 3. For @GetMapping("/{id}") Book get(@PathVariable long id), what happens for GET /api/books/abc?

    Type conversion fails before the method is invoked, which Spring reports as a 400.
  4. 4. Which response best fits a successful POST that creates a book?

    ResponseEntity.created(location) sets 201 and the Location header so the client knows where to find the new resource.
  5. 5. What does produces set to JSON on a mapping change when a client sends the header Accept: application/xml?

    produces declares what the endpoint can return. A request that accepts none of those types is rejected with 406.

Summary

  • @RestController marks a bean whose methods return the response body; @RequestMapping on the class sets a shared prefix.
  • @GetMapping, @PostMapping, @PutMapping, @PatchMapping and @DeleteMapping bind methods to HTTP verbs and paths.
  • @PathVariable takes values from the path and @RequestParam from the query string; failed conversions give 400.
  • Use ResponseEntity or @ResponseStatus for non-200 results: 201 with Location, 204 after delete, 404 when missing.
  • Content negotiation uses Accept and Content-Type; produces and consumes narrow it and lead to 406 and 415 when violated.
  • Keep controllers thin and return DTOs rather than entities.

Next: Request and Response Bodies with Jackson.