Spring Boot & Spring Cloud

Building REST APIs with Spring Boot 3: Controllers, DTOs, Status Codes and Clients

Intermediate8 min readUpdated

You will be able to build a clean JSON API with Spring Boot 3: map resources to controllers, use records as request and response bodies, return the right status codes and headers, handle pagination and content negotiation, configure CORS deliberately, and call other services with the RestClient introduced in Spring Framework 6.1.

What you will learn

  • Structure a resource-oriented API with @RestController and the composed mapping annotations
  • Use Java records as request and response DTOs and keep JPA entities out of the API contract
  • Return correct HTTP status codes, Location headers and ResponseEntity bodies for create, update and delete
  • Support pagination, sorting and content negotiation without leaking persistence details
  • Call downstream HTTP services with RestClient and declarative HTTP interface clients

Most Spring Boot services exist to expose an HTTP API that other programs call. Spring MVC makes the mechanics easy, which is exactly why so many APIs end up inconsistent: one endpoint returns 200 on creation, another returns entities with lazy-loading exceptions, a third accepts a page size of a million. This page walks through building an API that behaves like a well-designed one, from the controller layer through DTOs, status codes and pagination, and finishes with the client side, because a service in a system of services is also a consumer. It assumes Spring Boot 3.2 or later so that RestClient is available.

The request lifecycle in one paragraph

A request reaches the embedded Tomcat, passes through the servlet filter chain (security, CORS, tracing), and lands in the DispatcherServlet. The dispatcher asks its handler mappings which controller method matches the path and method, converts path variables, query parameters and the body into method arguments, invokes the method, and hands the return value to a message converter that writes JSON (Jackson by default). Exceptions bubble to exception handlers, which produce an error response. Everything you configure sits at one of those points, so knowing where a feature lives (filter, argument resolver, message converter, exception handler) tells you how to customise it.

Resource-oriented controllers

A REST API models resources addressed by URLs and manipulated with HTTP methods. Translate that to Spring by giving each aggregate its own controller with a class-level path and method-level verbs:

package com.example.shop.order;

import java.net.URI;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping("/api/orders")
class OrderController {

    private final OrderService orders;

    OrderController(OrderService orders) {
        this.orders = orders;
    }

    @GetMapping("/{id}")
    OrderResponse get(@PathVariable long id) {
        return OrderResponse.from(orders.get(id));   // throws OrderNotFoundException -> 404
    }

    @PostMapping
    ResponseEntity<OrderResponse> create(@RequestBody CreateOrderRequest request) {
        Order created = orders.create(request.customerId(), request.lines());
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                .path("/{id}").buildAndExpand(created.id()).toUri();
        return ResponseEntity.created(location).body(OrderResponse.from(created));
    }

    @PutMapping("/{id}/shipping-address")
    OrderResponse changeAddress(@PathVariable long id, @RequestBody Address address) {
        return OrderResponse.from(orders.changeShippingAddress(id, address));
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
    void cancel(@PathVariable long id) {
        orders.cancel(id);
    }
}

Several choices here are deliberate. Constructor injection keeps the controller testable without a container. The controller does no business logic; it translates HTTP into service calls and domain objects into responses. @ResponseStatus is used when the status is fixed, ResponseEntity when the status or headers depend on the outcome. The path uses nouns and a nested sub-resource (/shipping-address) rather than a verb such as /updateAddress.

Spring MVC matches paths with PathPatternParser since Boot 2.6, and Spring Framework 6 stopped matching trailing slashes by default: /api/orders/ no longer routes to /api/orders. If clients depend on the old behaviour, add a redirect or configure UrlHandlerFilter rather than reverting the global option.

Binding request data

AnnotationBindsTypical use
@PathVariableA URI template segmentResource identifiers
@RequestParamQuery or form parameterFilters, paging, flags; required = false and defaultValue for optional ones
@RequestBodyThe whole body via a message converterJSON payloads
@RequestHeaderA headerCorrelation ids, conditional requests
@ModelAttribute (implicit)Many query parameters into one objectSearch forms with several optional fields

Since Spring Framework 6.1 parameter names are no longer available through reflection unless the code is compiled with -parameters; the Boot parent POM and Gradle plugin set that flag, but a custom build must add it or every @PathVariable needs an explicit name.

Records as DTOs

Use records for both directions. They are immutable, concise, and Jackson (bundled by the web starter) serialises and deserialises them without annotations:

public record CreateOrderRequest(long customerId, List<OrderLine> lines) {
    public record OrderLine(String sku, int quantity) {}
}

public record OrderResponse(long id, String status, Money total, List<OrderLine> lines) {
    static OrderResponse from(Order order) {
        return new OrderResponse(order.id(), order.status().name(),
                order.total(), order.lines().stream().map(OrderLine::from).toList());
    }
}

Keeping JPA entities out of the contract avoids three recurring problems: lazy collections that explode into LazyInitializationException during serialisation, bidirectional associations that recurse forever, and accidental exposure of columns nobody meant to publish. The mapping methods are tedious to write but cheap to read; MapStruct generates them if the number grows.

A few Jackson settings that almost every API wants live in properties rather than annotations:

spring.jackson.default-property-inclusion=non_null
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.deserialization.fail-on-unknown-properties=false

java.time types serialise as ISO-8601 strings with the second setting; the first drops nulls from responses; the third is Boot's default and keeps old clients working when you add fields. When you need to forbid unknown fields on a specific request type, annotate that record with @JsonIgnoreProperties(ignoreUnknown = false).

Status codes and headers that mean something

HTTP semantics (RFC 9110) are the contract your clients already understand, so use them instead of inventing an envelope with "success": true:

SituationStatusNotes
Read succeeded200 OKBody is the representation
Created a resource201 CreatedLocation header; body optional but useful
Accepted for asynchronous processing202 AcceptedBody or header tells the client where to poll
Update or delete with nothing to return204 No ContentNo body at all
Malformed or invalid input400 Bad RequestOr 422 when syntax is fine but semantics are not
Unauthenticated / forbidden401 / 403Spring Security produces these
Unknown resource404 Not FoundAlso for valid ids the caller may not see, if you hide existence
Version conflict, duplicate409 ConflictOptimistic locking, unique constraints
Unexpected failure500 Internal Server ErrorNever leak stack traces

ResponseEntity is the tool for anything beyond a fixed status:

@GetMapping("/{id}")
ResponseEntity<OrderResponse> get(@PathVariable long id,
                                  @RequestHeader(value = "If-None-Match", required = false) String etag) {
    Order order = orders.get(id);
    String current = "\"" + order.version() + "\"";
    if (current.equals(etag)) {
        return ResponseEntity.status(304).eTag(current).build();
    }
    return ResponseEntity.ok().eTag(current).body(OrderResponse.from(order));
}

For the error side (translating exceptions into ProblemDetail responses) see the validation and error handling guide; the point here is that the happy path already needs to be precise. The HTTP status code reference in the Web subject lists every code with guidance on when to use it.

Pagination, sorting and filtering

Unbounded collections are the most common performance bug in APIs. Spring Data's Pageable can be injected straight into a controller method when the Data web support is on the classpath, which it is with spring-boot-starter-data-jpa:

@GetMapping
Page<OrderSummary> list(@RequestParam(required = false) String status,
                        @PageableDefault(size = 20, sort = "createdAt") Pageable pageable) {
    return orders.search(status, pageable).map(OrderSummary::from);
}

Clients send ?page=0&size=20&sort=createdAt,desc. Cap the size (spring.data.web.pageable.max-page-size, default 2000, is usually far too generous for an API) and consider returning a stable, minimal page shape. Since Spring Data 3.3, serialising a Page directly logs a warning because its JSON shape is not treated as a stable contract; set spring.data.web.pageable.serialization-mode=via_dto to get the simpler PagedModel structure, or wrap the page in your own record so that the contract does not move when a library does. Offset paging is fine for admin screens; for feeds and large tables prefer keyset pagination (?after=<last id>), which stays fast regardless of depth.

Filtering belongs in query parameters (?status=SHIPPED&customerId=42), never in the body of a GET. If a search is complex enough to need a body, model it as a POST /api/orders/search and document that it is safe and idempotent.

Content negotiation and versioning

Spring MVC picks the response format from the Accept header. With only Jackson present the answer is always JSON; add jackson-dataformat-xml and the same controller serves XML to a client that asks for it. Turning on the format query parameter (spring.mvc.contentnegotiation.favor-parameter=true) helps when browsers or proxies mangle headers.

Versioning has no single right answer. URL prefixes (/api/v2/orders) are the easiest to route, cache and document; a custom media type (Accept: application/vnd.shop.v2+json) keeps URLs stable at the cost of discoverability; a header (X-API-Version: 2) is simple but invisible to caches. Whichever you pick, version only on breaking changes and make additive changes (new optional fields) without a new version.

CORS

Browsers refuse cross-origin JavaScript calls unless the server opts in. A single-page application served from https://shop.example.com calling https://api.example.com needs a Cross-Origin Resource Sharing (CORS) policy:

@Configuration
class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("https://shop.example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Authorization", "Content-Type")
                .maxAge(3600);
    }
}

@CrossOrigin on a controller does the same per class or method. With Spring Security in the chain, CORS must also be enabled there (http.cors(Customizer.withDefaults())) so that the pre-flight OPTIONS request is not rejected before it reaches MVC. Wildcard origins combined with credentials are refused by browsers, and a wildcard alone means any website can call your API from a logged-in user's browser; list the origins you actually serve.

Calling other services

Spring Framework 6.1 added RestClient, a synchronous client with the fluent style of WebClient and no reactive dependency. Boot 3.2 auto-configures a RestClient.Builder that already carries the message converters and any RestClientCustomizer beans (Micrometer tracing headers, for example), so inject the builder rather than calling RestClient.create():

@Service
class InventoryClient {

    private final RestClient client;

    InventoryClient(RestClient.Builder builder,
                    @Value("${app.inventory.base-url}") String baseUrl) {
        this.client = builder.baseUrl(baseUrl).build();
    }

    StockLevel stockFor(String sku) {
        return client.get()
                .uri("/stock/{sku}", sku)
                .retrieve()
                .onStatus(HttpStatusCode::is4xxClientError,
                        (req, res) -> { throw new UnknownSkuException(sku); })
                .body(StockLevel.class);
    }
}

For a larger client surface, declare an HTTP interface and let Spring generate the implementation:

interface InventoryApi {
    @GetExchange("/stock/{sku}")
    StockLevel stock(@PathVariable String sku);

    @PostExchange("/reservations")
    Reservation reserve(@RequestBody ReservationRequest request);
}

@Bean
InventoryApi inventoryApi(RestClient.Builder builder, AppProperties props) {
    RestClient client = builder.baseUrl(props.inventory().baseUrl()).build();
    return HttpServiceProxyFactory
            .builderFor(RestClientAdapter.create(client))
            .build()
            .createClient(InventoryApi.class);
}

Whatever client you use, set connect and read timeouts (spring.http.client.connect-timeout and read-timeout in Boot 3.4+, or through the request factory before that). A client without a read timeout turns a slow dependency into thread exhaustion in your own service.

Common mistakes

Verbs in URLs and everything as POST. /api/getOrder?id=1 throws away caching, method semantics and the ability of tools to understand the API. Map reads to GET, creation to POST, full replacement to PUT, partial updates to PATCH, removal to DELETE.

Returning 200 for everything, with an error flag in the body. Clients, proxies, monitoring and retry logic all key off the status code. A 200 that means "failed" is invisible to all of them.

Exposing entities and relying on @JsonIgnore to hide fields. It works until someone adds a field, and it couples the schema to the API. Map to records.

Open Session in View masking lazy loading. Boot enables spring.jpa.open-in-view by default and logs a warning about it. It keeps the persistence context open during JSON serialisation, so lazy associations load one query at a time while the response is being written. Set it to false and load what the DTO needs in the service or repository.

Unbounded page sizes and missing timeouts. Both are fine in development and catastrophic under load; set limits on day one.

Ignoring -parameters. A custom Maven or Gradle setup without it makes every @PathVariable long id fail at runtime on Spring Framework 6.1+ with a message about missing parameter names.

Key takeaways

  • Model resources as controllers with class-level paths and method-level verbs; keep controllers thin and delegate to services.
  • Use records as request and response DTOs and never serialise JPA entities directly.
  • Return the status code and headers HTTP already defines: 201 with Location on creation, 204 for empty success, 4xx for client faults.
  • Bound every collection endpoint with pagination and expose a stable page shape; prefer keyset pagination for deep or high-traffic lists.
  • Enable CORS explicitly for the origins you serve, in MVC and in Spring Security.
  • Call other services with RestClient or an HTTP interface built from Boot's auto-configured builder, and always set timeouts.

Sources and further reading

Frequently asked questions

Should I return JPA entities directly from a controller?
Avoid it. Entities carry lazy associations that serialise badly or trigger extra queries, they expose database structure as an API contract, and any field you add for persistence reasons silently becomes public. A record-based DTO per endpoint lets the API and the schema evolve independently and makes the JSON shape explicit in code.
What is the difference between @Controller and @RestController?
@RestController is @Controller plus @ResponseBody. With plain @Controller, a String return value is interpreted as a view name to render; with @RestController every return value is written to the response body through an HttpMessageConverter, which for objects means JSON via Jackson. Use @RestController for APIs and @Controller for server-rendered HTML.
Which status code should a POST that creates a resource return?
201 Created, with a Location header pointing at the new resource and usually the created representation in the body. Return 200 only when the POST does not create anything addressable (for example a search or a command). For DELETE, 204 No Content is conventional when nothing is returned, and 404 if the resource was not found, unless you deliberately treat deletes as idempotent.
Is RestTemplate deprecated?
RestTemplate is in maintenance mode rather than deprecated: it still works and receives fixes, but new features go to RestClient (synchronous, fluent, introduced in Spring Framework 6.1) and WebClient (reactive). For a new Spring Boot 3.2+ service use RestClient, or an HTTP interface client backed by it, and migrate RestTemplate code when you touch it.