Spring Boot @RestController: from HTTP request to JSON response

A @RestController method looks like plain Java, but Spring MVC does a lot around it: it matches the request, converts parameters, writes the result as JSON and picks status codes for failures. This page explains that path, then runs a complete CRUD API, request binding, response control and the Jackson 3 rules that changed in Spring Boot 4.

Contents

How a request reaches a @RestController

A REST controller is a class whose methods each answer one kind of HTTP request, such as GET /api/products/2. You write ordinary Java methods with Java parameters and return values. Spring MVC turns the HTTP request into those parameters and turns the return value back into an HTTP response.

In a Spring Boot application, every request goes through the same path:

  1. The embedded Tomcat server accepts the connection and hands the request to one servlet, the DispatcherServlet, which Spring Boot registers on /.
  2. The DispatcherServlet asks the RequestMappingHandlerMapping which controller method matches. At startup, this mapping read every @GetMapping, @PostMapping and @RequestMapping, and built a table of path patterns, HTTP methods, and the content types each method consumes and produces.
  3. The RequestMappingHandlerAdapter calls the method. For each parameter, an argument resolver supplies the value: a path variable, a query parameter, a header, or the request body converted from JSON.
  4. The return value goes to a return value handler. Because @RestController includes @ResponseBody, the value is written to the response body by an HttpMessageConverter, usually the Jackson converter, which produces JSON.
  5. If anything fails, an exception resolver chooses the status code, such as 400 for a missing parameter or 415 for a body in a format the method does not accept.

@RestController itself is a small annotation. It is @Controller, which makes the class a bean found by component scanning, plus @ResponseBody, which says that return values are the response body and not the name of an HTML view.

The annotations used in REST controllers
AnnotationWhereWhat it does
@RestControllerClassRegisters the controller; return values become the response body
@RequestMappingClass or methodA path prefix on the class; on a method, a mapping for any HTTP method
@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMappingMethodMaps one HTTP method and path
@PathVariableParameterA {name} segment of the path
@RequestParamParameterA query parameter or form field
@RequestHeader, @CookieValueParameterA request header or a cookie
@RequestBodyParameterThe body, converted from JSON or another format
@ResponseStatusMethod or exception classThe status code to send instead of 200

The examples on this page use Spring Boot 4.1 with Spring Framework 7.0, Tomcat 11 and Jackson 3, with only spring-boot-starter-webmvc on the classpath. In Spring Boot 3.x this starter was called spring-boot-starter-web; Boot 4 still accepts the old name but marks it deprecated. Each program starts the application on a random free port, calls it with the JDK's HttpClient, prints each request and response, and shuts down.

A complete CRUD controller

A product catalogue is the smallest API that needs all five common operations: create, list, read, replace and delete. The program creates two products, changes one, deletes the other, and then reads the deleted one, so every status code a client normally sees appears once:

Java
package demo.crud;

import java.math.BigDecimal;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
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.util.UriComponentsBuilder;

@SpringBootApplication
public class CrudApi {

    public record Product(long id, String name, BigDecimal price) {}

    public record ProductForm(String name, BigDecimal price) {}

    @RestController
    @RequestMapping("/api/products")
    static class ProductController {
        private final Map<Long, Product> store = new ConcurrentSkipListMap<>();
        private final AtomicLong ids = new AtomicLong();

        @GetMapping
        public List<Product> list() {
            return List.copyOf(store.values());
        }

        @GetMapping("/{id}")
        public ResponseEntity<Product> get(@PathVariable long id) {
            return ResponseEntity.of(Optional.ofNullable(store.get(id)));
        }

        @PostMapping
        public ResponseEntity<Product> create(@RequestBody ProductForm form,
                                              UriComponentsBuilder uri) {
            long id = ids.incrementAndGet();
            Product saved = new Product(id, form.name(), form.price());
            store.put(id, saved);
            URI location = uri.path("/api/products/{id}").build(id);
            return ResponseEntity.created(location).body(saved);
        }

        @PutMapping("/{id}")
        public ResponseEntity<Product> replace(@PathVariable long id,
                                               @RequestBody ProductForm form) {
            if (!store.containsKey(id)) {
                return ResponseEntity.notFound().build();
            }
            Product updated = new Product(id, form.name(), form.price());
            store.put(id, updated);
            return ResponseEntity.ok(updated);
        }

        @DeleteMapping("/{id}")
        @ResponseStatus(HttpStatus.NO_CONTENT)
        public void delete(@PathVariable long id) {
            store.remove(id);
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void call(String method, String path, String json) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (json == null) {
            request.method(method, BodyPublishers.noBody());
        } else {
            request.method(method, BodyPublishers.ofString(json))
                   .header("Content-Type", "application/json");
        }
        HttpResponse<String> response = HTTP.send(request.build(), BodyHandlers.ofString());
        System.out.println(method + " " + path + (json == null ? "" : " " + json));
        System.out.println("  " + response.statusCode() + " " + response.body());
        response.headers().firstValue("Location")
                .ifPresent(l -> System.out.println("  Location: " + l.replace(base, "")));
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(CrudApi.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=WARN")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            call("POST", "/api/products", "{\"name\":\"Keyboard\",\"price\":49.90}");
            call("POST", "/api/products", "{\"name\":\"Mouse\",\"price\":19.50}");
            call("GET", "/api/products", null);
            call("PUT", "/api/products/2", "{\"name\":\"Wireless mouse\",\"price\":29.00}");
            call("DELETE", "/api/products/1", null);
            call("GET", "/api/products/1", null);
            call("GET", "/api/products", null);
        }
    }
}
Output
POST /api/products {"name":"Keyboard","price":49.90}
  201 {"id":1,"name":"Keyboard","price":49.90}
  Location: /api/products/1
POST /api/products {"name":"Mouse","price":19.50}
  201 {"id":2,"name":"Mouse","price":19.50}
  Location: /api/products/2
GET /api/products
  200 [{"id":1,"name":"Keyboard","price":49.90},{"id":2,"name":"Mouse","price":19.50}]
PUT /api/products/2 {"name":"Wireless mouse","price":29.00}
  200 {"id":2,"name":"Wireless mouse","price":29.00}
DELETE /api/products/1
  204 
GET /api/products/1
  404 
GET /api/products
  200 [{"id":2,"name":"Wireless mouse","price":29.00}]
  • Each POST returned 201 Created with a Location header, both set by ResponseEntity.created(location). Spring fills the UriComponentsBuilder parameter with the scheme, host and port of the current request, so the program built /api/products/1 without knowing its own address.
  • The records Product and ProductForm were converted to and from JSON with no annotations. Jackson uses a record's component names as the JSON field names. The prices stayed exactly 49.90 and 19.50 because they are BigDecimal, not double.
  • The DELETE returned 204 No Content with an empty body. The method returns void, and @ResponseStatus(HttpStatus.NO_CONTENT) replaced the default 200.
  • The GET for product 1 after the delete returned 404 with an empty body. ResponseEntity.of(Optional) returns 200 with the value when the Optional holds one, and 404 when it is empty.

A controller is a singleton. One instance serves every request, on many Tomcat threads at once, which is why the store is a ConcurrentSkipListMap and the id counter an AtomicLong. A plain HashMap field in a controller is a race condition. In a real application the store would be a repository bean, and the controller would hold no state of its own.

The controller is a static nested class so that each example fits in one file. Component scanning finds nested classes as long as they are static. In a project it would be a top-level class in its own file, in the package of the @SpringBootApplication class or below it.

Reading the request: path, query and headers

A search endpoint takes most of its input from the query string, with some values required, some optional and one repeated. The program sends four requests that bind, then three that do not, to show what the client receives in each case:

Java
package demo.binding;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class RequestBinding {

    public record Item(String sku) {}

    public record Search(String q, int page, List<String> tags, String sort, String client) {}

    @RestController
    static class CatalogController {

        // /items/ABC-123: the regex limits what the path variable accepts
        @GetMapping("/items/{sku:[A-Z]{3}-\\d+}")
        public Item item(@PathVariable String sku) {
            return new Item(sku);
        }

        @GetMapping("/search")
        public Search search(
                @RequestParam String q,                          // required
                @RequestParam(defaultValue = "0") int page,      // converted to int
                @RequestParam(required = false) List<String> tag, // ?tag=a&tag=b
                @RequestParam Optional<String> sort,             // optional, no default
                @RequestHeader(name = "X-Client", defaultValue = "unknown") String client) {
            return new Search(q, page, tag == null ? List.of() : tag,
                              sort.orElse("relevance"), client);
        }

        @GetMapping("/filters")
        public Map<String, String> filters(@RequestParam Map<String, String> all) {
            return all;   // every query parameter, by name
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void get(String path, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (headers.length > 0) {
            request.headers(headers);
        }
        HttpResponse<String> response = HTTP.send(request.build(), BodyHandlers.ofString());
        System.out.println("GET " + path);
        System.out.println("  " + response.statusCode() + " " + response.body());
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(RequestBinding.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF",
                            "spring.mvc.problemdetails.enabled=true")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            get("/items/ABC-123");
            get("/search?q=lamp&page=2&tag=desk&tag=led", "X-Client", "mobile");
            get("/search?q=lamp");
            get("/filters?color=red&size=M");
            System.out.println("--- requests that do not bind ---");
            get("/search");
            get("/search?q=lamp&page=two");
            get("/items/abc-123");
        }
    }
}
Output
GET /items/ABC-123
  200 {"sku":"ABC-123"}
GET /search?q=lamp&page=2&tag=desk&tag=led
  200 {"q":"lamp","page":2,"tags":["desk","led"],"sort":"relevance","client":"mobile"}
GET /search?q=lamp
  200 {"q":"lamp","page":0,"tags":[],"sort":"relevance","client":"unknown"}
GET /filters?color=red&size=M
  200 {"color":"red","size":"M"}
--- requests that do not bind ---
GET /search
  400 {"detail":"Required parameter 'q' is not present.","instance":"/search","status":400,"title":"Bad Request"}
GET /search?q=lamp&page=two
  400 {"detail":"Failed to convert 'page' with value: 'two'","instance":"/search","status":400,"title":"Bad Request"}
GET /items/abc-123
  404 {"detail":"No static resource items/abc-123.","instance":"/items/abc-123","status":404,"title":"Not Found"}
  • page=2 arrived as the int 2. Spring converts strings to the parameter type with its conversion service, which handles numbers, booleans, enums, dates, and any type with a valueOf method or a String constructor.
  • The two tag parameters became the list ["desk","led"]. In the second search, with no tag at all, the parameter was null, which the method turned into an empty list.
  • Optional<String> sort is optional without any attribute. defaultValue made page 0 and the client "unknown" when they were missing; a defaultValue also makes the parameter optional.
  • @RequestParam Map<String, String> received every query parameter in request order. It suits open-ended filters, but the method then has to check the names itself.
  • A missing q and the text two for an int both gave 400 Bad Request, with the reason in detail. The bodies use the RFC 9457 problem format because the program sets spring.mvc.problemdetails.enabled=true.
  • /items/abc-123 gave 404, not 400. The regular expression in {sku:[A-Z]{3}-\d+} is part of the path pattern, so a lower-case SKU matches no controller method. Spring then tried to serve the path as a static file and found none, hence No static resource.

The parameters have no names in their annotations: @RequestParam String q takes its name from the Java parameter. That only works when the code is compiled with javac -parameters, which keeps parameter names in the class file. The Spring Boot Maven and Gradle plugins turn it on, and these examples were compiled with it. Compiled without it, the same program answered every request to /items and /search with 500, and logged IllegalArgumentException: Name for argument of type [java.lang.String] not specified. Only /filters still worked, because a Map parameter needs no name. Spring Framework 6.1 removed the old fallback that read names from debug information, so a build that does not use the Boot plugins can break this way after an upgrade. Writing the name, as in @RequestParam("q"), avoids the problem completely.

Shaping the response: status, headers and content type

Most methods only need to return a value, but some responses need headers, a different status, or a format other than JSON. This controller has one method of each kind, and the second half of the program sends requests that Spring itself rejects:

Java
package demo.responses;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@SpringBootApplication
public class ResponseShapes {

    public record Report(String name, int rows) {}

    @RestController
    static class ReportController {

        @GetMapping("/hello")
        public String hello() {
            return "plain text";             // a String is written as text/plain
        }

        @GetMapping("/reports/{name}")
        public ResponseEntity<Report> report(@PathVariable String name) {
            if (name.equals("secret")) {
                throw new ResponseStatusException(HttpStatus.FORBIDDEN, "not yours");
            }
            return ResponseEntity.ok()
                    .eTag("\"v7\"")
                    .cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)))
                    .body(new Report(name, 42));
        }

        @GetMapping(path = "/reports/{name}.csv", produces = "text/csv")
        public String csv(@PathVariable String name) {
            return "name,rows\n" + name + ",42\n";
        }

        @PostMapping(path = "/reports", consumes = MediaType.APPLICATION_JSON_VALUE)
        @ResponseStatus(HttpStatus.ACCEPTED)
        public Report submit(@RequestBody Report report) {
            return report;
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void send(String method, String path, String... headers) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        String body = "";
        for (int i = 0; i < headers.length; i += 2) {
            if (headers[i].equals("body")) {
                body = headers[i + 1];
            } else {
                request.header(headers[i], headers[i + 1]);
            }
        }
        request.method(method, body.isEmpty() ? BodyPublishers.noBody()
                                              : BodyPublishers.ofString(body));
        HttpResponse<String> r = HTTP.send(request.build(), BodyHandlers.ofString());
        System.out.println(method + " " + path + " -> " + r.statusCode());
        for (String h : new String[] {"Content-Type", "ETag", "Cache-Control", "Allow"}) {
            r.headers().firstValue(h).ifPresent(v -> System.out.println("  " + h + ": " + v));
        }
        if (r.statusCode() < 400 && !r.body().isEmpty()) {
            System.out.println("  " + r.body().strip().replace("\n", "\\n"));
        }
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(ResponseShapes.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            send("GET", "/hello");
            send("GET", "/reports/sales");
            send("GET", "/reports/sales.csv");
            send("POST", "/reports", "Content-Type", "application/json",
                 "body", "{\"name\":\"q3\",\"rows\":7}");
            System.out.println("--- status codes Spring picks for you ---");
            send("GET", "/reports/secret");
            send("DELETE", "/reports/sales");
            send("GET", "/reports/sales", "Accept", "application/xml");
            send("POST", "/reports", "Content-Type", "text/plain", "body", "q3,7");
            send("GET", "/reports/sales/");
        }
    }
}
Output
GET /hello -> 200
  Content-Type: text/plain;charset=UTF-8
  plain text
GET /reports/sales -> 200
  Content-Type: application/json
  ETag: "v7"
  Cache-Control: max-age=300
  {"name":"sales","rows":42}
GET /reports/sales.csv -> 200
  Content-Type: text/csv;charset=UTF-8
  name,rows\nsales,42
POST /reports -> 202
  Content-Type: application/json
  {"name":"q3","rows":7}
--- status codes Spring picks for you ---
GET /reports/secret -> 403
  Content-Type: application/json
DELETE /reports/sales -> 405
  Content-Type: application/json
  Allow: GET
GET /reports/sales -> 406
  ETag: "v7"
  Cache-Control: max-age=300
POST /reports -> 415
  Content-Type: application/json
GET /reports/sales/ -> 404
  Content-Type: application/json
  • Returning a String produced text/plain, not a JSON string in quotes. The StringHttpMessageConverter comes before the Jackson converter, so a method that returns JSON text it built itself has to declare produces = "application/json".
  • ResponseEntity.ok().eTag(...).cacheControl(...) added ETag: "v7" and Cache-Control: max-age=300. Use ResponseEntity whenever the headers or the status depend on the request.
  • produces = "text/csv" set the content type of the CSV response. The same attribute takes part in matching: a request with Accept: text/csv is routed only to methods that produce it.
  • @ResponseStatus(HttpStatus.ACCEPTED) on the POST method changed the status to 202, while the body was still the returned record.
  • ResponseStatusException gave 403. It is the quickest way to fail with a particular status from inside a method.
  • DELETE on a path that only has GET gave 405 Method Not Allowed, with Allow: GET.
  • Accept: application/xml gave 406 Not Acceptable, because no converter on the classpath writes XML. The ETag header was already set: the method ran, and the failure came only when Spring tried to write its result.
  • A text/plain body sent to a method with consumes = "application/json" gave 415 Unsupported Media Type. That method never ran.
  • /reports/sales/ with a trailing slash gave 404. Spring Framework 6.0 stopped treating it as the same path as /reports/sales, so clients that add the slash need a mapping for it, or a redirect in front of the application.

The programs that show failures set logging.level.root=OFF. With the usual WARN, Spring also logs one line per rejected request, such as Resolved [HttpRequestMethodNotSupportedException: Request method 'DELETE' is not supported], which helps when debugging a client.

JSON with Jackson 3

Spring Boot 4 uses Jackson 3 for JSON, and Jackson 3 changed some defaults that Jackson 2 users rely on. A customer record with a date, an enum, a primitive and two annotated fields covers the cases that differ most often. The small @RestControllerAdvice returns Jackson's own error message, so the reason for each 400 is visible:

Java
package demo.json;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.LocalDate;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@SpringBootApplication
public class JsonMapping {

    public enum Status { ACTIVE, SUSPENDED }

    public record Customer(
            String name,
            @JsonProperty("joined_on") LocalDate joinedOn,
            Status status,
            int loyaltyPoints,
            String nickname,
            @JsonIgnore String passwordHash) {}

    @RestController
    static class CustomerController {
        @PostMapping("/customers")
        public Customer echo(@RequestBody Customer customer) {
            System.out.println("  controller received: " + customer);
            return customer;
        }
    }

    @RestControllerAdvice
    static class JsonErrors {
        @ExceptionHandler
        public ResponseEntity<String> unreadable(HttpMessageNotReadableException e) {
            String reason = e.getMostSpecificCause().getMessage().lines().findFirst().orElse("");
            return ResponseEntity.badRequest().body(reason);
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static void post(String json) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(base + "/customers"))
                .header("Content-Type", "application/json")
                .POST(BodyPublishers.ofString(json))
                .build();
        System.out.println("POST " + json);
        HttpResponse<String> response = HTTP.send(request, BodyHandlers.ofString());
        System.out.println("  " + response.statusCode() + " " + response.body());
    }

    public static void main(String[] args) throws Exception {
        try (var context = new SpringApplicationBuilder(JsonMapping.class)
                .properties("server.port=0", "spring.main.banner-mode=off",
                            "logging.level.root=OFF")
                .run(args)) {
            int port = ((WebServerApplicationContext) context).getWebServer().getPort();
            base = "http://localhost:" + port;

            post("{\"name\":\"Ana\",\"joined_on\":\"2024-03-01\",\"status\":\"ACTIVE\","
                 + "\"loyaltyPoints\":120,\"passwordHash\":\"x1\"}");
            post("{\"name\":\"Ben\",\"loyaltyPoints\":5,\"favouriteColour\":\"green\"}");
            post("{\"name\":\"Cy\"}");
            post("{\"name\":\"Di\",\"loyaltyPoints\":0,\"status\":\"BANNED\"}");
            post("{\"name\":\"Ed\",\"loyaltyPoints\":0,\"joined_on\":\"01/03/2024\"}");
            post("{\"name\":\"Fay\",");
        }
    }
}
Output
POST {"name":"Ana","joined_on":"2024-03-01","status":"ACTIVE","loyaltyPoints":120,"passwordHash":"x1"}
  controller received: Customer[name=Ana, joinedOn=2024-03-01, status=ACTIVE, loyaltyPoints=120, nickname=null, passwordHash=null]
  200 {"name":"Ana","joined_on":"2024-03-01","status":"ACTIVE","loyaltyPoints":120,"nickname":null}
POST {"name":"Ben","loyaltyPoints":5,"favouriteColour":"green"}
  controller received: Customer[name=Ben, joinedOn=null, status=null, loyaltyPoints=5, nickname=null, passwordHash=null]
  200 {"name":"Ben","joined_on":null,"status":null,"loyaltyPoints":5,"nickname":null}
POST {"name":"Cy"}
  400 Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
POST {"name":"Di","loyaltyPoints":0,"status":"BANNED"}
  400 Cannot deserialize value of type `demo.json.JsonMapping$Status` from String "BANNED": not one of the values accepted for Enum class: [SUSPENDED, ACTIVE]
POST {"name":"Ed","loyaltyPoints":0,"joined_on":"01/03/2024"}
  400 Text '01/03/2024' could not be parsed at index 0
POST {"name":"Fay",
  400 Unexpected end-of-input within/between Object entries
  • @JsonProperty("joined_on") renamed the field in both directions, and the LocalDate was read from and written as the ISO string "2024-03-01". Jackson 3 supports java.time types itself; Jackson 2 needed the separate jackson-datatype-jsr310 module, which Spring Boot added for you.
  • passwordHash was sent but arrived as null, and was not written back. @JsonIgnore works in both directions.
  • Ben's unknown field favouriteColour was ignored. Unknown properties do not fail by default in Jackson 3, which matches what Spring Boot already configured for Jackson 2.
  • Cy left out loyaltyPoints, an int, and got 400 with Cannot map `null` into type `int`. In Jackson 3, FAIL_ON_NULL_FOR_PRIMITIVES is on by default; in Jackson 2 it was off, and the field became 0. Running the program with spring.jackson.deserialization.fail-on-null-for-primitives=false, or with spring.jackson.use-jackson2-defaults=true, turned Cy's response into 200 with "loyaltyPoints":0. Using Integer for fields that clients may leave out is clearer than either.
  • An enum value that does not exist, a date in the wrong format and a truncated body each gave 400. Spring wraps them all in HttpMessageNotReadableException, so a handler for that one exception covers every unreadable body.
  • Missing fields of object types, such as Ben's joined_on and status, were written back as null. To leave them out of responses, set spring.jackson.default-property-inclusion=non_null.

Jackson 3 lives in the package tools.jackson instead of com.fasterxml.jackson. The annotations are the exception: they still come from com.fasterxml.jackson.annotation, as the imports here show, so records annotated for Jackson 2 work unchanged. Custom serializers and code that uses ObjectMapper directly need changes when upgrading from Spring Boot 3. So do the spring.jackson.read.* and spring.jackson.write.* properties, whose JSON-specific features moved under spring.jackson.json.

Return types and what they produce

The return type of a controller method decides how much of the response the method controls. These are the ones used in REST controllers:

Controller return types
Return typeStatusBest for
A record, class or collection200, or the one in @ResponseStatusMost reads; the simplest code
ResponseEntity<T>Any, chosen at run time201 with Location, 404 for a missing item, cache headers
void with @ResponseStatusThe annotated one, often 204Deletes and commands with no result
String200Plain text, not wrapped in JSON quotes
ProblemDetailThe one it containsError responses, usually from exception handlers
Resource, StreamingResponseBody200, or 206 for a rangeFiles and large downloads
SseEmitter, DeferredResult, CompletableFutureSet when the result arrivesServer-sent events and asynchronous results

A few more rules prevent surprises:

  • Thrown exceptions: an exception that no handler knows about becomes a 500. Map your own exceptions to statuses with @ResponseStatus or a @RestControllerAdvice, as shown in Spring Boot exception handling.
  • Entity classes: returning JPA entities directly ties the JSON to the database schema, and can trigger lazy loading while the response is written. Return records designed for the API instead.
  • Validation: @Valid on a @RequestBody runs Bean Validation only when spring-boot-starter-validation is on the classpath. Without it, the annotation is silently ignored.
  • Controller state: fields in a controller are shared by every request. Keep them final and thread-safe, or move the state to a service or a database.

Choosing the right tool for each part

Common needs in a REST controller and the feature that fits
NeedUse
Identify one resource@PathVariable, with a regex in the pattern if the format is fixed
Filters, paging and sorting@RequestParam with defaultValue or Optional
Data sent by the client@RequestBody with a record, plus @Valid
201, 404 or headers decided at run timeResponseEntity
A fixed status such as 204@ResponseStatus on the method
Failing with a status from inside a methodResponseStatusException, or your own exception and an advice
A format other than JSONproduces on the mapping
FilesMultipartFile in, Resource out, as in file upload and download

Related pages cover the layers around a controller: servlet filters and handler interceptors run before it, CORS controls which browser pages may call it, and API versioning lets two versions of a method live side by side.