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
In a Spring Boot application, every request goes through the same path:
- The embedded Tomcat server accepts the connection and hands the request to one servlet, the
, which Spring Boot registers onDispatcherServlet ./ - The
asks theDispatcherServlet which controller method matches. At startup, this mapping read everyRequestMappingHandlerMapping ,@GetMapping and@PostMapping , and built a table of path patterns, HTTP methods, and the content types each method consumes and produces.@RequestMapping - The
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.RequestMappingHandlerAdapter - The return value goes to a return value handler. Because
includes@RestController , the value is written to the response body by an@ResponseBody , usually the Jackson converter, which produces JSON.HttpMessageConverter - 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@Controller@ResponseBody
| Annotation | Where | What it does |
|---|---|---|
@RestController | Class | Registers the controller; return values become the response body |
@RequestMapping | Class or method | A path prefix on the class; on a method, a mapping for any HTTP method |
@GetMapping@PostMapping@PutMapping@PatchMapping@DeleteMapping | Method | Maps one HTTP method and path |
@PathVariable | Parameter | A {name} |
@RequestParam | Parameter | A query parameter or form field |
@RequestHeader@CookieValue | Parameter | A request header or a cookie |
@RequestBody | Parameter | The body, converted from JSON or another format |
@ResponseStatus | Method or exception class | The 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-webmvcspring-boot-starter-webHttpClient
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:
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);
}
}
}
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
returned 201 Created with aPOST header, both set byLocation . Spring fills theResponseEntity.created(location) parameter with the scheme, host and port of the current request, so the program builtUriComponentsBuilder without knowing its own address./api/products/1 - The records
andProduct were converted to and from JSON with no annotations. Jackson uses a record's component names as the JSON field names. The prices stayed exactlyProductForm and49.90 because they are19.50 , notBigDecimal .double - The
returned 204 No Content with an empty body. The method returnsDELETE , andvoid replaced the default 200.@ResponseStatus(HttpStatus.NO_CONTENT) - The
for product 1 after the delete returned 404 with an empty body.GET returns 200 with the value when theResponseEntity.of(Optional) holds one, and 404 when it is empty.Optional
A controller is a singleton. One instance serves every request, on many Tomcat threads at once, which is why the store is a ConcurrentSkipListMapAtomicLongHashMap
The controller is a static@SpringBootApplication
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:
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");
}
}
}
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"}
arrived as thepage=2 2. Spring converts strings to the parameter type with its conversion service, which handles numbers, booleans, enums, dates, and any type with aint method or avalueOf constructor.String- The two
parameters became the listtag . In the second search, with no["desk","led"] at all, the parameter wastag , which the method turned into an empty list.null is optional without any attribute.Optional<String> sort madedefaultValue 0 and the clientpage when they were missing; a"unknown" also makes the parameter optional.defaultValue received every query parameter in request order. It suits open-ended filters, but the method then has to check the names itself.@RequestParam Map<String, String>- A missing
and the textq for antwo both gave 400 Bad Request, with the reason inint . The bodies use the RFC 9457 problem format because the program setsdetail .spring.mvc.problemdetails.enabled=true gave 404, not 400. The regular expression in/items/abc-123 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{sku:[A-Z]{3}-\d+} .No static resource
The parameters have no names in their annotations: @RequestParam String qjavac -parameters/items/searchIllegalArgumentException: Name for argument of type [java.lang.String] not specified/filtersMap@RequestParam("q")
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:
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/");
}
}
}
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
producedString , not a JSON string in quotes. Thetext/plain comes before the Jackson converter, so a method that returns JSON text it built itself has to declareStringHttpMessageConverter .produces = "application/json" addedResponseEntity.ok().eTag(...).cacheControl(...) andETag: "v7" . UseCache-Control: max-age=300 whenever the headers or the status depend on the request.ResponseEntity set the content type of the CSV response. The same attribute takes part in matching: a request withproduces = "text/csv" is routed only to methods that produce it.Accept: text/csv on the@ResponseStatus(HttpStatus.ACCEPTED) method changed the status to 202, while the body was still the returned record.POST gave 403. It is the quickest way to fail with a particular status from inside a method.ResponseStatusException on a path that only hasDELETE gave 405 Method Not Allowed, withGET .Allow: GET gave 406 Not Acceptable, because no converter on the classpath writes XML. TheAccept: application/xml header was already set: the method ran, and the failure came only when Spring tried to write its result.ETag- A
body sent to a method withtext/plain gave 415 Unsupported Media Type. That method never ran.consumes = "application/json" 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./reports/sales
The programs that show failures set logging.level.root=OFFWARNResolved [HttpRequestMethodNotSupportedException: Request method 'DELETE' is not supported]
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
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\",");
}
}
}
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
renamed the field in both directions, and the@JsonProperty("joined_on") was read from and written as the ISO stringLocalDate . Jackson 3 supports"2024-03-01" types itself; Jackson 2 needed the separatejava.time module, which Spring Boot added for you.jackson-datatype-jsr310 was sent but arrived aspasswordHash , and was not written back.null works in both directions.@JsonIgnore- Ben's unknown field
was ignored. Unknown properties do not fail by default in Jackson 3, which matches what Spring Boot already configured for Jackson 2.favouriteColour - Cy left out
, anloyaltyPoints , and got 400 withint . In Jackson 3,Cannot map `null` into type `int` is on by default; in Jackson 2 it was off, and the field became 0. Running the program withFAIL_ON_NULL_FOR_PRIMITIVES , or withspring.jackson.deserialization.fail-on-null-for-primitives=false , turned Cy's response into 200 withspring.jackson.use-jackson2-defaults=true . Using"loyaltyPoints":0 for fields that clients may leave out is clearer than either.Integer - 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
, so a handler for that one exception covers every unreadable body.HttpMessageNotReadableException - Missing fields of object types, such as Ben's
andjoined_on , were written back asstatus . To leave them out of responses, setnull .spring.jackson.default-property-inclusion=non_null
Jackson 3 lives in the package tools.jacksoncom.fasterxml.jacksoncom.fasterxml.jackson.annotationObjectMapperspring.jackson.read.*spring.jackson.write.*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:
| Return type | Status | Best for |
|---|---|---|
| A record, class or collection | 200, or the one in @ResponseStatus | Most reads; the simplest code |
ResponseEntity<T> | Any, chosen at run time | 201 with Location |
void@ResponseStatus | The annotated one, often 204 | Deletes and commands with no result |
String | 200 | Plain text, not wrapped in JSON quotes |
ProblemDetail | The one it contains | Error responses, usually from exception handlers |
ResourceStreamingResponseBody | 200, or 206 for a range | Files and large downloads |
SseEmitterDeferredResultCompletableFuture | Set when the result arrives | Server-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
or a@ResponseStatus , as shown in@RestControllerAdviceSpring 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:
on a@Valid runs Bean Validation only when@RequestBody is on the classpath. Without it, the annotation is silently ignored.spring-boot-starter-validation - 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
| Need | Use |
|---|---|
| Identify one resource | @PathVariable |
| Filters, paging and sorting | @RequestParamdefaultValueOptional |
| Data sent by the client | @RequestBody@Valid |
| 201, 404 or headers decided at run time | ResponseEntity |
| A fixed status such as 204 | @ResponseStatus |
| Failing with a status from inside a method | ResponseStatusException |
| A format other than JSON | produces |
| Files | MultipartFileResource |
Related pages cover the layers around a controller: