Building a JSON API the Spring way, next to the Express you know: controllers and mappings, path variables, query parameters, request bodies and status codes, records as DTOs with Jackson 3, validation, errors as RFC 9457 problem details, calling other APIs with RestClient and HTTP interface clients, Boot 4's built-in API versioning, filters and interceptors, and virtual threads. Every example was run with Spring Boot 4.2.0 on Java 25, and every response shown is what curl really got.
Try it yourself. Each example is the starter project from chapter 11 plus the files shown. Start it with ./mvnw spring-boot:run in one terminal, wait for Started ShopApplication, then type the curl lines in another. curl -s prints just the body; curl -si adds the status line and headers. Stop the app with Ctrl+C before the next example.
10 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.
In Express you register a function per route: app.get("/products", (req, res) => res.json(products)). In Spring MVC you write a class annotated @RestController, and each method annotated with a mapping (@GetMapping("/products")) handles one route. Whatever the method returns becomes the response body, turned into JSON by Jackson. You don't call res.json; you return an object.
The mental model: a controller is a router file where each handler is a typed method. Spring reads the annotations at startup and builds the routing table, the same table Express builds from your app.get calls. The difference is that the parameters are typed and filled in for you (path variables, query parameters, the parsed body), and the return type documents the response.
@RestController makes the class a bean (it's found by component scanning, like @Service in chapter 12) and says every method's return value is the response body.
@GetMapping("/products") maps GET /products to all(). It returns a List<Product>, and Jackson writes it as a JSON array: [{"id":1,"name":"Keyboard","priceCents":4999},{"id":2,"name":"Mouse","priceCents":1950}]. The record's component names became the JSON keys.
/hello returns a String, which is written as-is with Content-Type: text/plain;charset=UTF-8. Status 200, with the headers Tomcat adds.
A path nobody mapped gets Spring Boot's default error response, a 404 as JSON: {"timestamp":…,"status":404,"error":"Not Found","path":"/nope"}. That's Boot's fallback error handling; you'll replace it with problem details below.
There's no app.listen(8080): the starter's embedded Tomcat is already listening on 8080, and the controller is one more bean in the context.
#Path variables, query parameters, bodies and status codes
Added
Real endpoints need input and more than one kind of answer. Spring binds each piece of the request to a method parameter by annotation, and ResponseEntity lets you choose the status code and headers when the default 200 isn't right:
@PathVariable: a piece of the path, /products/{id}. Spring converts it to the parameter's type, so a non-number is rejected with 400 before your code runs.
@RequestParam: a query parameter, ?maxPrice=2000. Required by default; required = false makes it optional (then it's null, so use Long, not long).
@RequestBody: the JSON body, parsed into an object by Jackson.
ResponseEntity<T>: the body plus status and headers. ResponseEntity.of(optional) gives 200 or 404; ResponseEntity.created(uri) gives 201 Created with a Location header, the correct answer to a POST that creates something.
@RequestMapping("/products") on the class prefixes every method, like mounting an Express router. @GetMapping with no path is GET /products.
?maxPrice=2000 binds to Long maxPrice and the stream keeps only the mouse: [{"id":2,"name":"Mouse","priceCents":1950}]. Without the parameter it's null and nothing is filtered.
GET /products/1 binds 1 to long id and returns the keyboard. GET /products/99 finds nothing, so ResponseEntity.of(Optional.empty()) answers 404 with an empty body (Content-Length: 0).
The POST body is parsed by Jackson into a NewProduct record. The response is 201 with Location: /products/3 and the created product as the body, {"id":3,"name":"Webcam","priceCents":6500}. The next GET /products lists all three.
/products/abc can't be converted to a long, so Spring rejects it with 400 Bad Request without calling one at all: type conversion is part of the binding.
The map is a ConcurrentHashMap and the ids come from an AtomicLong because a controller is a singleton used by many request threads at once (chapter 12's scope rule); a plain HashMap and long counter would break under concurrent requests. A real service keeps this in a database (chapter 14).
What goes over the wire should be a DTO (data transfer object): a class shaped for the API, separate from your database entity, so you can change one without breaking the other and never leak a field by accident (a password hash, an internal flag). Records are perfect DTOs: one line, immutable, and Jackson reads and writes them by their components.
Spring Boot 4 uses Jackson 3 (tools.jackson packages; Boot 3 used Jackson 2, com.fasterxml.jackson). The behaviours that matter day to day:
Unknown fields in a request are ignored by Boot's mapper, so a client that sends extra fields doesn't break you.
Dates and times (LocalDate, Instant) are written as ISO-8601 strings like "2026-11-01".
null fields are included as null unless you configure otherwise.
Renaming a field in JSON is @JsonProperty("snake_name") on the component; the annotations package is still com.fasterxml.jackson.annotation in Jackson 3.
The request record has three components. The JSON sends customer and items, plus a giftWrap field the record doesn't have.
Jackson builds an OrderRequest through its constructor, ignores giftWrap (Boot configures the mapper not to fail on unknown properties), and leaves couponCode as null because it wasn't sent.
The response record is written in component order. @JsonProperty("order_id") renames the first key; itemCount is computed from the list, 2.
couponCode is null and still appears: "couponCode":null. deliveryDate is a LocalDate and becomes "2026-12-01"; the Instant becomes "2026-11-26T15:00:00Z". No date-format configuration was needed.
The DTOs live next to the controller and are shaped for the API: the client sees order_id and itemCount, not whatever a database table happens to contain.
Never trust a request body. Jakarta Bean Validation (Hibernate Validator 9.1 in Boot 4.2, from the validation starter) lets you put the rules on the DTO as annotations, @NotBlank, @Positive, @Size, @Email, @Min, and @Valid on the controller parameter makes Spring check them before your method runs. A failing request never reaches your code; it gets a 400.
It's the Java version of a Zod or Joi schema in an Express app, with the rules on the type instead of in a separate schema object.
The rules live on the record: name must not be blank and at most 40 characters, priceCents must be greater than 0. @ResponseStatus(HttpStatus.CREATED) sets the success status without a ResponseEntity.
A valid body passes, and the method echoes it back.
The second request breaks both rules. @Valid makes Spring validate after parsing, the method is never called, and Boot's default error body says only "status":400,"error":"Bad Request". That's deliberately vague: by default Boot doesn't tell clients which field failed. The next topic fixes that properly.
The third request isn't even valid for the type: "cheap" can't become a long, so Jackson fails while parsing and the answer is also 400, before validation runs.
Validation also works on @RequestParam and @PathVariable (@Min(1) long id), and on any Spring bean method with @Validated on the class.
#Error handling with @RestControllerAdvice and ProblemDetail
Added
APIs need consistent, useful errors: the same shape for every failure, with enough detail for the client to act on. The standard shape is RFC 9457 problem details (it replaced RFC 7807): a JSON object with the standard members type, title, status, detail and instance (all optional), served as application/problem+json, plus any extra fields you add. Spring has a ProblemDetail class for it.
Two pieces work together:
spring.mvc.problemdetails.enabled=true makes Spring's own errors (validation, bad JSON, unsupported method) come back as problem details instead of Boot's {"timestamp","status","error","path"} body. It's off by default in Boot 4.2.
A @RestControllerAdvice class with @ExceptionHandler methods maps your own exceptions to responses, in one place for the whole app. It's Express's error-handling middleware (app.use((err, req, res, next) => …)), selected by exception type.
$ curl -si localhost:8080/products/7
HTTP/1.1 404
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Thu, 26 Nov 2026 15:24:48 GMT
{"detail":"No product with id 7","status":404,"title":"Product not found","type":"https://example.com/problems/product-not-found","productId":7}
$ curl -s -X POST localhost:8080/products -H "Content-Type: application/json" -d '{"name":"","priceCents":-5}'
{"detail":"The request has invalid fields.","status":400,"title":"Invalid request","fields":{"name":"must not be blank","priceCents":"must be greater than 0"}}
$ curl -s -X POST localhost:8080/products -H "Content-Type: application/json" -d '{"name":'
{"detail":"Failed to read request","status":400,"title":"Bad Request"}
$ curl -s -X DELETE localhost:8080/products/1
{"detail":"Method 'DELETE' is not supported.","status":405,"title":"Method Not Allowed"}
What’s happening
The controller just throwsProductNotFoundException for a missing id. It doesn't build an error response; the advice class does that for every controller in the app.
ApiErrors is a @RestControllerAdvice. Its notFound method handles that exception type (taken from the parameter) and returns a ProblemDetail: status 404, the message as detail, a title, a type URI that documents the error, and an extra productId field, sent as Content-Type: application/problem+json.
ApiErrors also extends ResponseEntityExceptionHandler, the Spring class that turns Spring MVC's own exceptions into problem details. With problem details switched on, Boot registers one of these itself, and its handler for validation errors would win over an ordinary @ExceptionHandler of yours (Spring just says "detail":"Invalid request content."). Extending the class and overriding handleMethodArgumentNotValid is the documented way to customise it, and Boot then backs off and uses yours (chapter 12's @ConditionalOnMissingBean at work).
So the invalid POST gets the field errors as a sorted fields map: {"name":"must not be blank","priceCents":"must be greater than 0"}. The client knows exactly what to fix.
Broken JSON ({"name":) and an unmapped method (DELETE) are Spring's own errors, handled by the inherited methods as problem details: 400Failed to read request, and 405Method 'DELETE' is not supported.. One shape for every failure is the point: clients parse errors one way.
#Calling other APIs: RestClient and HTTP interface clients
Added
Services call other services. Spring has had three HTTP clients, and which one you'd pick has changed:
Client
Style
Status in Boot 4.2
RestTemplate
blocking, template methods
deprecated in Framework 7.1 / Boot 4.2; you'll still read lots of it
WebClient
reactive (Mono/Flux), from WebFlux
for reactive apps
RestClient
blocking, fluent
the recommended client for Spring MVC apps (Framework 6.1+)
HTTP interface clients
a Java interface with @GetExchange methods; Spring implements it
the recommended declarative client (Boot 4 registers them with @ImportHttpServices); it replaces Spring Cloud OpenFeign, which is now feature-complete
RestClient is the closest to fetch: build a request, send it, read the body as a type. The interface style is like generating an API client from a spec: you describe the remote API as methods, and Spring makes the calls. In Boot 4 both come from the spring-boot-starter-restclient starter, and Boot configures them (JSON with the same Jackson mapper, timeouts, base URLs from properties).
To keep this example self-contained, the app calls itself: a small "supplier" controller plays the remote API on the same server.
Add this to the starter's pom.xml, inside <dependencies>:
packagecom.example.shop;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RestController;// Plays the role of another company's API.@RestControllerclassSupplierController{recordStock(String sku,int available){}@GetMapping("/supplier/stock/{sku}")Stockstock(@PathVariableString sku){returnnewStock(sku, sku.length()*3);}}
SupplierController is the pretend remote API: GET /supplier/stock/KB-1 returns {"sku":"KB-1","available":12} (4 characters × 3).
RestClient: the controller asks for Boot's auto-configured RestClient.Builder (don't use RestClient.create(), which skips Boot's configuration), sets the base URL (this app's own port, read with @Value) and builds a client. rest.get().uri(…).retrieve().body(Stock.class) sends the request, checks the status (4xx and 5xx throw an exception), and converts the JSON into a record, like await (await fetch(url)).json() with types.
HTTP interface: SupplierApi is just an interface. @HttpExchange("/supplier") sets a path prefix and @GetExchange("/stock/{sku}") describes one call. @ImportHttpServices(group = "supplier", types = SupplierApi.class) tells Spring to generate an implementation and register it as a bean, so AvailabilityController can inject it like any service.
The group's base URL comes from configuration, spring.http.serviceclient.supplier.base-url, which is where a real deployment would put the other service's address. Here it points back at this app's own port.
Both calls return the same data: KB-1: 12 in stock (RestClient) and MOUSE-22: 24 in stock (HTTP interface). In a real service you'd also set timeouts (spring.http.serviceclient.supplier.read-timeout) and decide what to do when the other side is slow or down (chapter 17).
APIs change, and old clients must keep working. The usual strategies are a path segment (/v1/products), a header (X-API-Version: 2), a query parameter (?version=2) or a media type parameter (Accept: application/json;version=2). Before Spring Framework 7 you built this yourself, usually as separate controllers under /v1 and /v2. Spring Framework 7 / Boot 4 have versioning built in: you choose how the version is read with spring.mvc.apiversion.use.*, and each mapping can say which version it serves with version = "…".
Two methods map the same path, /products/{id}, for versions 1 and 2. Version 2 changes the response shape (the price becomes a Money object), which is exactly the kind of breaking change that needs a new version.
spring.mvc.apiversion.use.header=X-API-Version tells Spring to read the version from that header. Version 1 gets {"id":1,"name":"Keyboard","priceCents":4999}; version 2 gets the nested price.
With no header, spring.mvc.apiversion.default=1 applies, so old clients that never sent a version keep getting version 1. Without a default, a request with no version is rejected with 400.
Version 3 isn't served by any mapping (the supported versions are detected from the controllers), so it's rejected with 400 too.
/health-check has no version, so it answers for every version, including the default.
Express middleware runs code around every request: logging, auth, request ids, CORS. Spring MVC has two layers for that job:
A servlet filter sits in front of Spring entirely, in Tomcat's filter chain. It sees every request, including ones for paths no controller handles, and works with the raw request and response. Spring Security is a filter chain (chapter 16). Extend OncePerRequestFilter and make it a bean.
A HandlerInterceptor runs inside Spring MVC, after a controller method was chosen, so it knows which handler will run. It has preHandle, postHandle and afterCompletion. Register it with a WebMvcConfigurer.
The mental model: a filter is middleware mounted with app.use() before the router; an interceptor is middleware that runs after routing, like a per-route middleware that knows the matched route.
src/main/java/com/example/shop/Web.java
packagecom.example.shop;importjava.io.IOException;importjakarta.servlet.FilterChain;importjakarta.servlet.ServletException;importjakarta.servlet.http.HttpServletRequest;importjakarta.servlet.http.HttpServletResponse;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.filter.OncePerRequestFilter;importorg.springframework.web.method.HandlerMethod;importorg.springframework.web.servlet.HandlerInterceptor;importorg.springframework.web.servlet.config.annotation.InterceptorRegistry;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;@ComponentclassRequestIdFilterextendsOncePerRequestFilter{@OverrideprotectedvoiddoFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain)throwsServletException,IOException{String id = request.getHeader("X-Request-Id");
response.setHeader("X-Request-Id", id !=null? id :"generated-1");
chain.doFilter(request, response);}}classHandlerNameInterceptorimplementsHandlerInterceptor{@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler){if(handler instanceofHandlerMethod method){
response.setHeader("X-Handler", method.getBeanType().getSimpleName()+"#"+ method.getMethod().getName());}returntrue;}}@ConfigurationclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddInterceptors(InterceptorRegistry registry){
registry.addInterceptor(newHandlerNameInterceptor());}}@RestControllerclassPingController{@GetMapping("/ping")Stringping(){return"pong";}}
RequestIdFilter runs for every request. It copies the caller's X-Request-Id to the response (or makes one up), then calls chain.doFilter to pass the request on, the equivalent of Express's next(). Forgetting that call means the request never reaches Spring.
HandlerNameInterceptor runs only once Spring MVC has picked a handler; handler is then a HandlerMethod, so it can name the controller and method in an X-Handler header.
GET /ping passes through both: HTTP/1.1 200, X-Request-Id: abc-123 from the filter and X-Handler: PingController#ping from the interceptor.
GET /missing matches no controller. The filter runs (X-Request-Id: generated-1), and the interceptor reports X-Handler: BasicErrorController#error: when nothing handles a path, Tomcat forwards the request to /error, which Spring Boot's BasicErrorController handles, and that forward goes through the interceptor too. That's where Boot's default 404 body comes from.
Rule of thumb: request-level concerns that don't care about the controller (ids, logging, security, CORS, compression) go in filters; concerns tied to handlers (per-endpoint metrics, annotations on controller methods) go in interceptors. For error handling, use @RestControllerAdvice instead of either.
Spring MVC gives each request its own thread. Classically that's a platform thread from Tomcat's pool (200 by default), and while your code waits for a database or another service, the thread waits too. That's simple to write and debug, and it limits how many slow requests you can have in flight at once. Node.js took the other road: one thread, never blocking, everything asynchronous.
Java 21's virtual threads (chapter 09) remove most of that limit: they're cheap enough to have one per request even with tens of thousands of requests waiting. In Spring Boot that's one property, spring.threads.virtual.enabled=true: Tomcat then runs each request on a new virtual thread, and your blocking code stays exactly as it is.
The same controller with spring.threads.virtual.enabled=true: Tomcat now hands each request to a new virtual thread, so it prints virtual thread? true.
Nothing else changed. That's the selling point over reactive code: the same blocking style, much higher concurrency for I/O-bound work.
AdvancedWhere WebFlux still fits
Where WebFlux still fits. Spring WebFlux is Spring's reactive web stack (on Netty, with Mono and Flux), closer to Node's model: a few event-loop threads and non-blocking I/O end to end. Before virtual threads it was the way to handle very high concurrency in Java. Now most teams can stay on MVC with virtual threads. WebFlux still makes sense for streaming (server-sent events, WebSockets with backpressure), for apps that are already reactive, and when the whole stack, database driver included, is non-blocking. Mixing them is the trap: one blocking call inside a WebFlux handler stalls an event-loop thread, exactly like a synchronous fs.readFileSync in a Node server.
@DeleteMapping maps the DELETE method. ConcurrentHashMap.remove returns the removed value, or null if the key wasn't there, which decides the status.
ResponseEntity<Void> says there's never a body. The first delete removes the keyboard: 204. The second finds nothing: 404. (-w "%{http_code}" makes curl print just the status.)
The list now has only {"2":"Mouse"}: a Map with Long keys is written as a JSON object, so the keys become strings.
?Your turn: map a conflict to 409
Creating a product whose name already exists should answer 409 Conflict as a problem detail with the clashing name in a name field. Throw a DuplicateProductException from the controller and handle it in an advice.
Set.add returns false when the value is already there, which makes the duplicate check one line; lower-casing makes Webcam and webcam clash. The set comes from ConcurrentHashMap.newKeySet() so concurrent requests are safe.
The first POST succeeds with 201. The second throws DuplicateProductException.
The advice maps it to a 409 problem detail with the title, the message as detail, and the extra name field. The controller never deals with HTTP error formatting.
?Your turn: validate a query parameter
GET /products/search?q=…&limit=… should require q to be at least 2 characters and limit between 1 and 50 (default 10). Return the parameters it accepted, and make bad values answer 400.
Constraint annotations on @RequestParam parameters are checked by Spring MVC's built-in method validation (Framework 6.1+), so no @Validated is needed on the controller.
q=key passes and limit takes its default: {"q":"key","limit":10}.
q=k is too short and limit=500 is above 50: both 400. Leaving out q entirely is also 400, because a @RequestParam is required unless it has a default or required = false.