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.
The request lifecycle
A controller, properly written
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);
}
}
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
| Annotation | Binds | Example |
|---|---|---|
@PathVariable | A URI template segment | /books/{id} |
@RequestParam | Query string or form field | ?q=java&page=2 |
@RequestBody | The deserialised request body | JSON → record |
@RequestHeader | A single header | @RequestHeader("X-Tenant") |
@CookieValue | A cookie | — |
@ModelAttribute | Multiple query params into one object | Search filters |
@RequestPart | One part of a multipart upload | File + metadata |
@ResponseStatus | The status for a normal return | 204 NO_CONTENT |
// 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
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.
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);
}
}
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
| Situation | Status | How |
|---|---|---|
| Read succeeded | 200 | Return the object |
| Resource created | 201 + Location | ResponseEntity.created(uri) |
| Accepted for async processing | 202 | ResponseEntity.accepted() |
| Deleted / updated, no body | 204 | @ResponseStatus(NO_CONTENT) |
| Malformed or invalid input | 400 | Bean Validation (ch. 7) |
| Not authenticated | 401 | Security filter (ch. 10) |
| Authenticated but not allowed | 403 | Security filter |
| Does not exist | 404 | Throw a domain exception, map it in advice |
| Conflicts with current state | 409 | Duplicate key, optimistic lock failure |
| Rate limited | 429 | Filter or gateway |
| Unexpected failure | 500 | Never on purpose |
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
spring:
data:
web:
pageable:
default-page-size: 25
max-page-size: 100 # protects you from ?size=1000000
one-indexed-parameters: false
# Pageable is resolved from the query string automatically curl "localhost:8080/api/books?page=0&size=20&sort=title,asc&sort=price,desc"
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
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
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
@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();
}
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.
@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));
}
}
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
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
@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
| Setting | Why |
|---|---|
server.shutdown=graceful | In-flight requests finish before the JVM exits during a rolling deploy |
server.compression.enabled=true | Gzip for JSON responses over ~2 KB |
server.tomcat.threads.max | Default 200; tune with your downstream capacity, not upward by reflex |
spring.threads.virtual.enabled=true | Java 21 virtual threads — big win for I/O-bound services |
server.forward-headers-strategy=framework | Correct scheme and host behind a load balancer |
Checklist
- DTOs in and out; entities never cross the controller boundary.
- Correct status codes, and a
Locationheader 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.