Chapter 06

Building REST APIs

Spring MVC is a big surface area, but you can be productive with about twelve annotations. This chapter covers those twelve, and the design decisions around them that you will live with for years.

⏱ 22 min readLevel: beginner → intermediateCore chapter

The request lifecycle

Request path from the client through Tomcat, the filter chain, the DispatcherServlet with handler mapping, adapter, argument resolvers, your controller and a message converter
Everything between the socket and your method — worth knowing when something is intercepted before you see it.

A controller, properly written

catalog/BookController.java
package com.bitsnippets.bookstore.catalog;

import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

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

    private final BookService bookService;

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

    @GetMapping("/{id}")
    public BookResponse findById(@PathVariable Long id) {
        return BookResponse.from(bookService.require(id));
    }

    @GetMapping
    public Page<BookResponse> search(@RequestParam(required = false) String q,
                                     @RequestParam(required = false) String category,
                                     Pageable pageable) {
        return bookService.search(q, category, pageable).map(BookResponse::from);
    }

    @PostMapping
    public ResponseEntity<BookResponse> create(@Valid @RequestBody BookRequest request,
                                               UriComponentsBuilder uriBuilder) {
        Book created = bookService.create(request.toCommand());

        URI location = uriBuilder.path("/api/books/{id}")
                                 .buildAndExpand(created.getId())
                                 .toUri();

        return ResponseEntity.created(location)          // 201 + Location header
                             .body(BookResponse.from(created));
    }

    @PutMapping("/{id}")
    public BookResponse replace(@PathVariable Long id,
                                @Valid @RequestBody BookRequest request) {
        return BookResponse.from(bookService.replace(id, request.toCommand()));
    }

    @PatchMapping("/{id}")
    public BookResponse update(@PathVariable Long id,
                               @Valid @RequestBody BookPatchRequest request) {
        return BookResponse.from(bookService.patch(id, request));
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        bookService.delete(id);
    }
}
Controllers should be boring

A controller translates HTTP into a method call and back. No business rules, no transactions, no repository access. If a controller method is longer than about ten lines, the logic belongs in the service.

The annotations you actually need

AnnotationBindsExample
@PathVariableA URI template segment/books/{id}
@RequestParamQuery string or form field?q=java&page=2
@RequestBodyThe deserialised request bodyJSON → record
@RequestHeaderA single header@RequestHeader("X-Tenant")
@CookieValueA cookie—
@ModelAttributeMultiple query params into one objectSearch filters
@RequestPartOne part of a multipart uploadFile + metadata
@ResponseStatusThe status for a normal return204 NO_CONTENT
binding many query parameters into one object
// GET /api/books?q=java&minPrice=10&maxPrice=50&inStock=true
public record BookSearchFilter(String q,
                               BigDecimal minPrice,
                               BigDecimal maxPrice,
                               Boolean inStock) { }

@GetMapping
public Page<BookResponse> search(@ModelAttribute BookSearchFilter filter,
                                 Pageable pageable) {
    return bookService.search(filter, pageable).map(BookResponse::from);
}

Never expose your entities

Returning an entity from a controller is a security bug waiting to happen

Add a passwordHash field to the entity and it appears in the API response. Add a lazy association and Jackson triggers it, or fails. Rename a column and you break every client. Entities model your database; DTOs model your contract. Keep them separate.

catalog/dto/BookRequest.java
public record BookRequest(

        @NotBlank @Size(max = 200)
        String title,

        @NotNull
        Long authorId,

        @NotNull @DecimalMin("0.00") @Digits(integer = 8, fraction = 2)
        BigDecimal price,

        @Size(max = 5)
        Set<String> categories) {

    public CreateBookCommand toCommand() {
        return new CreateBookCommand(title, authorId, price,
                                     categories == null ? Set.of() : categories);
    }
}
catalog/dto/BookResponse.java
public record BookResponse(Long id,
                           String title,
                           String authorName,
                           BigDecimal price,
                           Set<String> categories,
                           Instant createdAt) {

    public static BookResponse from(Book book) {
        return new BookResponse(
                book.getId(),
                book.getTitle(),
                book.getAuthor().getName(),
                book.getPrice(),
                book.getCategories().stream().map(Category::getName)
                    .collect(Collectors.toUnmodifiableSet()),
                book.getCreatedAt());
    }
}

Status codes that mean something

SituationStatusHow
Read succeeded200Return the object
Resource created201 + LocationResponseEntity.created(uri)
Accepted for async processing202ResponseEntity.accepted()
Deleted / updated, no body204@ResponseStatus(NO_CONTENT)
Malformed or invalid input400Bean Validation (ch. 7)
Not authenticated401Security filter (ch. 10)
Authenticated but not allowed403Security filter
Does not exist404Throw a domain exception, map it in advice
Conflicts with current state409Duplicate key, optimistic lock failure
Rate limited429Filter or gateway
Unexpected failure500Never on purpose
Do not return 200 with an error inside

200 OK with {"success": false} defeats every HTTP client, proxy, retry policy and monitoring tool between you and the caller. Use the status line — that is what it is for.

Pagination and sorting

application.yml
spring:
  data:
    web:
      pageable:
        default-page-size: 25
        max-page-size: 100          # protects you from ?size=1000000
        one-indexed-parameters: false
terminal
# Pageable is resolved from the query string automatically
curl "localhost:8080/api/books?page=0&size=20&sort=title,asc&sort=price,desc"
Do not serialise Page directly

Boot warns about this: Page's JSON shape is an implementation detail and has already changed between versions. Wrap it in your own response record so the contract is yours, or set spring.data.web.pageable.serialization-mode=via-dto on recent versions.

public record PageResponse<T>(List<T> content, int page, int size,
                              long totalElements, int totalPages) {

    public static <T> PageResponse<T> from(Page<T> page) {
        return new PageResponse<>(page.getContent(), page.getNumber(),
                                  page.getSize(), page.getTotalElements(),
                                  page.getTotalPages());
    }
}

Controlling the JSON

application.yml
spring:
  jackson:
    default-property-inclusion: non_null    # omit nulls from responses
    serialization:
      write-dates-as-timestamps: false      # ISO-8601 instead of epoch millis
      fail-on-empty-beans: false
    deserialization:
      fail-on-unknown-properties: true      # reject unexpected fields loudly
    time-zone: UTC
per-field control
public record BookResponse(

        Long id,

        @JsonProperty("book_title")                       // rename in JSON
        String title,

        @JsonFormat(pattern = "yyyy-MM-dd")               // custom format
        LocalDate publishedOn,

        @JsonInclude(JsonInclude.Include.NON_EMPTY)       // omit when empty
        Set<String> categories,

        @JsonIgnore                                       // never serialise
        String internalNote) { }

File uploads

catalog/CoverController.java
@PostMapping(value = "/{id}/cover", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Void> uploadCover(@PathVariable Long id,
                                        @RequestPart("file") MultipartFile file,
                                        @RequestPart("meta") @Valid CoverMeta meta) {

    if (file.isEmpty()) {
        throw new BadRequestException("File is empty");
    }
    if (!List.of("image/png", "image/jpeg").contains(file.getContentType())) {
        throw new UnsupportedMediaTypeException(file.getContentType());
    }
    coverService.store(id, file.getInputStream(), file.getSize(), meta);
    return ResponseEntity.noContent().build();
}
application.yml
spring:
  servlet:
    multipart:
      max-file-size: 5MB
      max-request-size: 10MB

Validate the declared content type and the actual bytes — a client can claim anything. Never build a filesystem path from the uploaded filename.

Calling other services

RestTemplate is in maintenance mode. Use RestClient (Boot 3.2+) for synchronous calls; it has a fluent API and the same underlying infrastructure.

common/InventoryClient.java
@Component
public class InventoryClient {

    private final RestClient client;

    public InventoryClient(RestClient.Builder builder, InventoryProperties props) {
        this.client = builder
                .baseUrl(props.baseUrl())
                .requestFactory(timeouts(props.timeout()))
                .defaultHeader("X-Service", "bookstore")
                .build();
    }

    public StockLevel stockFor(String isbn) {
        return client.get()
                .uri("/stock/{isbn}", isbn)
                .retrieve()
                .onStatus(status -> status.value() == 404,
                          (req, res) -> { throw new StockNotFoundException(isbn); })
                .body(StockLevel.class);
    }

    private static ClientHttpRequestFactory timeouts(Duration timeout) {
        return ClientHttpRequestFactories.get(
                ClientHttpRequestFactorySettings.DEFAULTS
                        .withConnectTimeout(Duration.ofSeconds(2))
                        .withReadTimeout(timeout));
    }
}
Always set timeouts

The default is infinite. One slow dependency will exhaust your entire thread pool and take the service down while the dependency is merely degraded. Two seconds to connect and five to read is a reasonable starting point for internal calls.

Declarative HTTP clients

interface-based client
public interface InventoryApi {

    @GetExchange("/stock/{isbn}")
    StockLevel stockFor(@PathVariable String isbn);

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

@Configuration
public class HttpClientConfig {

    @Bean
    InventoryApi inventoryApi(RestClient.Builder builder) {
        RestClient client = builder.baseUrl("http://inventory").build();
        return HttpServiceProxyFactory
                .builderFor(RestClientAdapter.create(client))
                .build()
                .createClient(InventoryApi.class);
    }
}

CORS

common/WebConfig.java
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("https://bookstore.example.com")   // never "*" with credentials
                .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
                .allowedHeaders("Authorization", "Content-Type")
                .exposedHeaders("Location")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

If Spring Security is on the classpath it must also be told about CORS — see chapter 10. A CORS config that works without security and breaks with it is a very common half-hour of confusion.

Small things that matter

SettingWhy
server.shutdown=gracefulIn-flight requests finish before the JVM exits during a rolling deploy
server.compression.enabled=trueGzip for JSON responses over ~2 KB
server.tomcat.threads.maxDefault 200; tune with your downstream capacity, not upward by reflex
spring.threads.virtual.enabled=trueJava 21 virtual threads — big win for I/O-bound services
server.forward-headers-strategy=frameworkCorrect scheme and host behind a load balancer

Checklist

  • DTOs in and out; entities never cross the controller boundary.
  • Correct status codes, and a Location header on every 201.
  • Page size capped server-side.
  • Timeouts on every outbound call.
  • Controllers contain no business logic and no transactions.
  • Graceful shutdown enabled before you deploy to Kubernetes.

Why should @RestController methods not return JPA entities?

It works technically, which is why it is tempting. But every schema change becomes a breaking API change, lazy associations blow up during serialisation, and any sensitive column added later is exposed by default. A DTO costs ten lines and removes all three problems.