Spring MVC REST API Guide to Building Clean Endpoints
Build a clean Spring MVC REST API: records at the edge, validation, one error format, pagination, caching headers, security, testing and what to avoid.

A REST API is a contract with people you cannot ask. Clients compile against your field names, retry on your status codes and parse your error bodies, so every inconsistency you ship becomes a workaround in someone else's code. Spring MVC gives you enough rope to build an API that is consistent or one that is not, and the difference is a handful of conventions applied from the first endpoint: one shape per resource, one place for errors, explicit status codes, and tests that read like the contract.
This guide builds a small task-tracking API on Spring Boot 4 and Java 25, one decision at a time. It covers controllers and records, validation, a single error format, creating and updating resources, pagination and filtering, caching headers, CORS, security, versioning and testing, and ends with the mistakes that cost the most time. The examples use Spring MVC (the servlet stack); reactive and virtual-thread alternatives and the API style question are covered elsewhere. If you have not built a Boot project yet, start with the Spring Boot guide. The snippets were not compiled in a build for this post, so treat them as reviewed examples and compile them against your versions; the annotations used are stable across Spring Framework 6 and 7.
How a request reaches your controller
You write less glue when you know what runs. A request reaches the DispatcherServlet, which asks the handler mappings which method handles that URL and verb, runs interceptors, resolves the method's arguments (path variables, query parameters, the JSON body through an HttpMessageConverter), calls your method, and writes the return value back through a converter. Exceptions go to the exception resolvers. Every error named in this guide is one of those stages complaining: a 405 is the mapping stage, a 415 is the converter stage, a 400 on a body is deserialization, and a 400 with field details is argument validation. The detailed flow, with filters and interceptors, is in how Spring MVC handles a request.
Design the URLs before the code
Decide the resource vocabulary first, because URLs are the hardest thing to change later. A workable convention:
| Operation | Request | Success | Notes |
|---|---|---|---|
| List tasks | GET /api/tasks?status=OPEN&page=0&size=20 | 200 | Filters and paging in the query string |
| Get one | GET /api/tasks/{id} | 200 | 404 when absent |
| Create | POST /api/tasks | 201 and Location | Server assigns the id |
| Replace or update | PUT /api/tasks/{id} | 200 or 204 | Idempotent |
| Partial update | PATCH /api/tasks/{id} | 200 | Only the fields sent |
| Delete | DELETE /api/tasks/{id} | 204 | 404 or 204 when already gone, pick one and document it |
| An action that is not CRUD | POST /api/tasks/{id}/complete | 200 | A verb as a sub-resource, honestly named |
Use plural nouns, lowercase and hyphens, and no verbs in the path except for actions. Do not put the version in the resource name or the database id format in the contract unless you mean to keep it forever. The reasoning behind these rules is in resource URL design and the wider set of rules in REST API design rules for Java teams.
One controller per resource, records at the edge
The API's request and response shapes should be their own types, separate from the JPA entity. Java records make that cheap: immutable, no boilerplate, and a constructor Jackson can use.
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.time.Instant;
import java.time.LocalDate;
public final class TaskDtos {
private TaskDtos() { }
public record CreateTask(
@NotBlank @Size(max = 120) String title,
@Size(max = 2000) String description,
@FutureOrPresent LocalDate dueDate) { }
public record UpdateTask(
@NotBlank @Size(max = 120) String title,
@Size(max = 2000) String description,
LocalDate dueDate,
TaskStatus status) { }
public record TaskView(
long id,
String title,
String description,
LocalDate dueDate,
TaskStatus status,
Instant createdAt) { }
}The create type carries only what a client may set. There is no id, no createdAt and no status, so a client cannot choose them, which also closes the mass-assignment hole where a request sets a field it should not. The view type is what comes back. Keep three types even when they look similar today: they diverge the first time you add an internal column.
The controller maps HTTP to service calls and does nothing else:
import dev.javahacks.tasks.TaskDtos.CreateTask;
import dev.javahacks.tasks.TaskDtos.TaskView;
import dev.javahacks.tasks.TaskDtos.UpdateTask;
import jakarta.validation.Valid;
import java.net.URI;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping("/api/tasks")
class TaskController {
private final TaskService tasks;
TaskController(TaskService tasks) {
this.tasks = tasks;
}
@GetMapping
Page<TaskView> list(@RequestParam(required = false) TaskStatus status, Pageable page) {
return tasks.list(status, page);
}
@GetMapping("/{id}")
TaskView get(@PathVariable long id) {
return tasks.get(id);
}
@PostMapping
ResponseEntity<TaskView> create(@Valid @RequestBody CreateTask request) {
TaskView created = tasks.create(request);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(created.id()).toUri();
return ResponseEntity.created(location).body(created);
}
@PutMapping("/{id}")
TaskView update(@PathVariable long id, @Valid @RequestBody UpdateTask request) {
return tasks.update(id, request);
}
@DeleteMapping("/{id}")
ResponseEntity<Void> delete(@PathVariable long id) {
tasks.delete(id);
return ResponseEntity.noContent().build();
}
}Notice the choices. Methods that always succeed with 200 return the body directly. Methods whose status varies, create and delete, return ResponseEntity. @Valid on the body parameter triggers validation before the method runs. Pageable is resolved from page, size and sort query parameters automatically when Spring Data's web support is on, which it is in Boot. And the controller has no try or catch: errors are thrown, and one class handles them.
Let the service decide what is missing
A controller asking "is it null?" for every lookup is a controller doing the service's job. Make the service throw a domain exception, and map the exception to HTTP in one place:
import dev.javahacks.tasks.TaskDtos.CreateTask;
import dev.javahacks.tasks.TaskDtos.TaskView;
import dev.javahacks.tasks.TaskDtos.UpdateTask;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(readOnly = true)
class TaskService {
private final TaskRepository repository;
TaskService(TaskRepository repository) {
this.repository = repository;
}
Page<TaskView> list(TaskStatus status, Pageable page) {
Page<Task> found = status == null ? repository.findAll(page) : repository.findByStatus(status, page);
return found.map(TaskService::toView);
}
TaskView get(long id) {
return toView(find(id));
}
@Transactional
TaskView create(CreateTask request) {
Task task = new Task(request.title(), request.description(), request.dueDate());
return toView(repository.save(task));
}
@Transactional
TaskView update(long id, UpdateTask request) {
Task task = find(id);
task.change(request.title(), request.description(), request.dueDate(), request.status());
return toView(task);
}
@Transactional
void delete(long id) {
repository.delete(find(id));
}
private Task find(long id) {
return repository.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
}
private static TaskView toView(Task t) {
return new TaskView(t.getId(), t.getTitle(), t.getDescription(), t.getDueDate(),
t.getStatus(), t.getCreatedAt());
}
}The update method has no save call. Inside a transaction, a managed entity's changes are flushed on commit, so changing the fields is enough. The mapping to a view happens inside the service, where the entity is still attached; mapping in the controller would touch lazy associations outside the transaction. See never serialize entities directly below.
One advice class for every error
Without a plan, each failure produces a different body: a stack trace from the default handler, a bare {"error": "..."} from a hand-written one, an HTML page from a servlet error. Pick one format and produce it everywhere. The standard is RFC 9457 Problem Details, and Spring has ProblemDetail for it:
import java.net.URI;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(TaskNotFoundException.class)
ProblemDetail notFound(TaskNotFoundException ex) {
ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
p.setTitle("Task not found");
p.setType(URI.create("https://api.example.com/problems/task-not-found"));
return p;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
ProblemDetail invalid(MethodArgumentNotValidException ex) {
ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Request validation failed");
p.setTitle("Invalid request");
List<FieldIssue> issues = ex.getBindingResult().getFieldErrors().stream()
.map(f -> new FieldIssue(f.getField(), f.getDefaultMessage()))
.toList();
p.setProperty("errors", issues);
return p;
}
record FieldIssue(String field, String message) { }
}A failed validation now answers like this:
HTTP/1.1 400
Content-Type: application/problem+json
{"type":"about:blank","title":"Invalid request","status":400,"detail":"Request validation failed",
"instance":"/api/tasks","errors":[{"field":"title","message":"must not be blank"}]}The shape is identical for every error, so a client writes one handler. A few rules for the content: detail is for humans and never includes a stack trace or SQL; type is a stable URI clients can switch on, and the machine-readable part is the status plus type plus your errors extension. Spring can also generate Problem Details for its own exceptions (405, 415, missing parameters) when you set spring.mvc.problemdetails.enabled=true, which gives the framework's errors the same shape without code. Add a catch-all @ExceptionHandler(Exception.class) that logs with a correlation id and returns a generic 500, so an unexpected failure never leaks internals. The individual exceptions, with causes, are covered in MethodArgumentNotValidException, missing request parameters, unreadable JSON, 415 errors and 405 errors.
Status codes that tell the truth
Clients branch on status codes, so use the precise ones:
| Situation | Status |
|---|---|
| Read or update succeeded | 200 |
| Created | 201 with Location |
| Succeeded, nothing to return | 204 |
| Malformed JSON or a failed validation | 400 |
| Not authenticated | 401 |
| Authenticated, not allowed | 403 |
| No such resource | 404 |
| Wrong verb for the URL | 405 |
| Conflict with current state (duplicate, stale version) | 409 |
Unsupported Content-Type | 415 |
| Semantically wrong but well-formed | 422 (or 400, choose one and keep it) |
| Too many requests | 429 with Retry-After |
| Unexpected failure | 500 |
Two that teams get wrong: returning 200 with {"success": false} (it defeats every HTTP-aware tool, from caches to monitoring), and using 404 for authorization failures to hide that a resource exists, which is a legitimate choice only when you decide it deliberately.
Pagination and filtering
Returning a Page from a controller serializes Spring Data's internal structure, which includes fields you did not choose and which has changed shape between versions. Prefer your own envelope:
public record PageResponse<T>(java.util.List<T> items, int page, int size, long total) {
public static <T> PageResponse<T> of(org.springframework.data.domain.Page<T> p) {
return new PageResponse<>(p.getContent(), p.getNumber(), p.getSize(), p.getTotalElements());
}
}Cap the page size so a client cannot ask for a million rows. In Boot that is configuration:
spring.data.web.pageable.default-page-size=20
spring.data.web.pageable.max-page-size=100Offset paging (page and size) is simple and fine for small to medium tables. For large or fast-changing data, offset paging gets slow and skips or repeats rows when data changes between requests; use keyset (cursor) paging there, as in cursor pagination. Whitelist sortable fields instead of passing sort straight to the database, or a client can sort by a column with no index.
Validation beyond the body
@Valid handles request bodies. For query and path parameters, put constraints on the parameter and add @Validated to the class. Since Spring Framework 6.1 the framework validates method parameters itself and throws HandlerMethodValidationException, which you handle like the one above:
@GetMapping("/search")
List<TaskView> search(@RequestParam @Size(min = 2, max = 50) String q) {
return tasks.search(q);
}Cross-field rules belong in a class-level constraint or in the service. Business rules, such as "a completed task cannot be reopened after 30 days", belong in the service as well, and throw an exception mapped to 409. A validator annotation is the wrong tool for anything that needs the database.
Caching and conditional requests
GET responses can be cached, and conditional requests save bandwidth. The cheapest option is an ETag computed from the response body:
@Bean
FilterRegistrationBean<ShallowEtagHeaderFilter> etag() {
var bean = new FilterRegistrationBean<>(new ShallowEtagHeaderFilter());
bean.addUrlPatterns("/api/*");
return bean;
}A client that sends If-None-Match with the previous ETag gets a 304 with no body. The server still does the work of building the response, so this saves transfer, not computation. For computation savings, return explicit headers from the controller with ResponseEntity.ok().cacheControl(CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic()) where the data allows it, and handle If-Match on updates to prevent lost writes. The full set is in ETag and conditional requests and HTTP cache headers.
CORS without guessing
A browser app on another origin triggers a preflight OPTIONS request, and an API without CORS configuration answers it with an error the browser reports as a CORS failure. Configure it in one place, with explicit origins:
@Bean
WebMvcConfigurer cors() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Authorization", "Content-Type")
.maxAge(3600);
}
};
}If Spring Security is on the classpath, CORS must also be enabled in the security filter chain, or the preflight is rejected before MVC sees it. Never combine allowedOrigins("*") with credentials. The common failures are in Spring Boot CORS errors.
Never serialize entities directly
It is tempting to return the JPA entity from the controller. It works for a day. Then a lazy collection is touched outside the transaction and throws, a bidirectional relationship (Task to Project and back) recurses until the stack overflows, the entity gains an internal column that now appears in the API, and a client depends on a field you meant to rename. The cure is the one already used: map to a view record inside the service. If you want to see the recursion failure and its fixes, it is covered here. Mapping by hand is a few lines per type and trivially debuggable; a mapping library is fine once you have many types, as long as the mapping runs inside the transaction.
Securing the API
An API that returns data for users needs authentication and authorization, and Spring Security is the standard answer. A minimal resource-server setup that accepts JWT bearer tokens:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
class SecurityConfig {
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // stateless bearer-token API
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.GET, "/api/tasks/**").hasAuthority("SCOPE_tasks:read")
.requestMatchers("/api/tasks/**").hasAuthority("SCOPE_tasks:write")
.anyRequest().denyAll())
.oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()));
return http.build();
}
}Two points. Disabling CSRF protection is correct only for APIs that authenticate with a header token and never with a cookie; a cookie-authenticated API needs CSRF protection. And anyRequest().denyAll() makes new endpoints closed by default, which is the safer failure. Authorization on the data matters as much as on the route: a user who may read tasks must still only read their own, so filter by the authenticated principal in the service and test it.
Versioning
Plan for change, because the first breaking change comes sooner than expected. Additive changes (a new optional field, a new endpoint) need no version: tell clients to ignore unknown fields. Breaking changes (renaming a field, changing a type) need a way to coexist. The common options are a path prefix (/api/v2/tasks), a header, or a media type. Spring Framework 7 adds first-class API versioning to the MVC mapping annotations, so a version can be declared on the handler instead of duplicated in paths; check the reference for your release for the exact configuration. Whichever you choose, keep the old version running for a stated period and measure its traffic before removing it.
Partial updates with PATCH
PUT replaces a resource, so the client must send every field. Clients that edit one field want PATCH, and the question is how to say "leave this alone" versus "set this to null". A Java record cannot tell a missing JSON field from an explicit null, so a naive PatchTask(String title, String description) clears the description whenever the client omits it. Two sound options exist.
The first is JSON Merge Patch (RFC 7396): the body is a JSON object, present fields overwrite, null removes, absent fields are untouched. Read the body as a JsonNode and apply it onto the current view:
@PatchMapping(path = "/{id}", consumes = "application/merge-patch+json")
TaskView patch(@PathVariable long id, @RequestBody JsonNode patch) {
return tasks.patch(id, patch);
}@Transactional
TaskView patch(long id, JsonNode patch) {
Task task = find(id);
if (patch.has("title")) task.rename(patch.get("title").asText());
if (patch.has("description")) {
task.describe(patch.get("description").isNull() ? null : patch.get("description").asText());
}
if (patch.has("status")) task.moveTo(TaskStatus.valueOf(patch.get("status").asText()));
return toView(task);
}Validate inside the entity methods (rename rejects blank), because the body bypasses bean validation. The second option is to avoid generic patching: expose the real operations as sub-resources (POST /api/tasks/{id}/complete, PUT /api/tasks/{id}/assignee). Small, named operations are easier to authorize, audit and test than a patch that can change anything. We prefer them when the operations are few and have rules.
Actions that are not CRUD, and slow work
Some operations do not map onto a resource update: complete, archive, export. Model them as a POST to an action path and keep the verb honest in the name. When the work takes longer than a request should, do not hold the connection. Accept the job, answer 202 Accepted with a link to a status resource, and let the client poll:
@PostMapping("/exports")
ResponseEntity<Void> startExport(@RequestBody ExportRequest request) {
String jobId = exports.submit(request); // returns immediately, runs elsewhere
URI status = URI.create("/api/exports/" + jobId);
return ResponseEntity.accepted().location(status).build();
}
@GetMapping("/exports/{jobId}")
ResponseEntity<ExportStatus> status(@PathVariable String jobId) {
ExportStatus s = exports.status(jobId);
return s.done()
? ResponseEntity.status(HttpStatus.SEE_OTHER).location(s.resultUri()).build()
: ResponseEntity.ok(s);
}While running, the status endpoint returns 200 with a state and progress; when finished it redirects with 303 to the result. A client that follows redirects needs no special handling. Keep jobs in a table, not in memory, so a restart does not lose them.
Safe retries with idempotency keys
GET, PUT and DELETE are idempotent by definition: repeating them has the same effect. POST is not, and networks fail after the server has acted but before the client hears. The client retries, and the order is created twice. The fix is an Idempotency-Key header: the client sends a unique value per logical operation, and the server stores the response keyed by it and replays the stored response on a repeat.
@PostMapping
ResponseEntity<TaskView> create(@RequestHeader(name = "Idempotency-Key", required = false) String key,
@Valid @RequestBody CreateTask request) {
return idempotency.execute(key, () -> {
TaskView created = tasks.create(request);
return ResponseEntity.created(locationOf(created)).body(created);
});
}The idempotency component inserts the key into a table with a unique constraint before doing the work and stores the result afterwards; a concurrent duplicate hits the constraint and waits or returns 409. The mechanics, including the expiry of old keys, are in idempotent REST endpoints. Apply it to the endpoints where a duplicate costs money or creates visible duplicates, and not to every POST.
Content negotiation
Spring picks a response format from the Accept header. JSON is the default with Jackson on the classpath. To offer a second representation, such as CSV for an export, declare it on the mapping and write a converter or return the bytes yourself:
@GetMapping(path = "/export", produces = "text/csv")
ResponseEntity<byte[]> exportCsv() {
String csv = tasks.toCsv();
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"tasks.csv\"")
.body(csv.getBytes(java.nio.charset.StandardCharsets.UTF_8));
}A request with Accept: application/json for that path gets a 406 Not Acceptable, which is the correct answer. Prefer the Accept header over a .csv suffix or a ?format= parameter; Spring Framework 6 disabled suffix matching by default for good reason.
Uploads and large responses
File uploads arrive as multipart/form-data. Bind them with MultipartFile and set explicit limits, because the defaults are generous:
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=6MB@PostMapping(path = "/{id}/attachments", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
ResponseEntity<Void> attach(@PathVariable long id, @RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty() || !List.of("image/png", "application/pdf").contains(file.getContentType())) {
throw new ResponseStatusException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "Only PNG and PDF are accepted");
}
attachments.store(id, file.getOriginalFilename(), file.getInputStream());
return ResponseEntity.noContent().build();
}Never use getOriginalFilename() as a path: generate your own storage name, or you have a path traversal bug. A client-supplied Content-Type is a claim and not a fact; sniff the bytes if it matters. For large downloads, return a StreamingResponseBody or a Resource so the response is written in chunks, and the heap does not hold the whole file.
Observability from day one
An API you cannot see is an API you cannot fix. Three things pay for themselves immediately.
A request id. Generate one per request in a filter, put it in the logging context (MDC) and echo it in a response header. Every log line for that request then carries the id, and a user's complaint becomes a single search. Spring Boot 3.2 and later add trace and span ids to the MDC when Micrometer tracing is on the classpath.
Metrics. Actuator with Micrometer records request counts and latency per route and status with no code: http.server.requests. Alert on the rate of 5xx and on the p95 and p99 latency of the busiest routes, not on averages.
Structured logs. One JSON object per line, with the request id, the route and the outcome, lets you query logs by field. Spring Boot 3.4 added built-in structured logging formats (logging.structured.format.console=ecs).
management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.endpoint.health.probes.enabled=true
logging.structured.format.console=ecsKeep Actuator on a separate management port or behind authentication, since /actuator/env and /actuator/heapdump are sensitive.
Document the API from the code
Clients need documentation that cannot drift from the implementation. The usual route is an OpenAPI description generated from the controllers and served beside the app, or the reverse, an OpenAPI file written first and server stubs generated from it. Either way, the description is checked in or published by CI, and a contract test compares behavior to it. The tools and trade-offs of generating from code or from a spec are in OpenAPI 3 for Java. Documentation should include the error format, the pagination envelope, the authentication scheme and examples of a failing request, because those are what integrators read first.
Rate limiting and abuse
A public API will be abused sooner or later, by a bug in a client loop as often as by an attacker. Put rate limiting at the edge (an API gateway or reverse proxy) so excess traffic never reaches the JVM, and answer with 429 and a Retry-After header. Inside the application, bound the expensive things directly: maximum page size, maximum request body size (server.tomcat.max-swallow-size, spring.servlet.multipart.*), maximum number of items in a bulk request and a timeout on outbound calls. A POST /api/tasks/bulk that accepts a list should reject more than, say, 500 items with 413 or 400 and a message that states the limit.
A project layout that scales
A layout that keeps each concern findable, with packages by feature and not by layer:
src/main/java/dev/javahacks/
tasks/
TaskController.java # HTTP only
TaskService.java # rules, transactions
TaskRepository.java # persistence
Task.java # entity
TaskDtos.java # request and response records
TaskNotFoundException.java
config/
SecurityConfig.java
WebConfig.java
common/
ApiExceptionHandler.javaPackage-private classes (as in the examples above, with no public) mean other features cannot reach into the task internals; only the controller's HTTP surface is public in effect. When the second feature arrives, copy the shape, not the code, and move shared code to common only when three features need it.
Test the contract, not the class
A good API test sends HTTP and asserts on the response a client would see. MockMvc does this without starting a server, and a @WebMvcTest loads only the web layer. The service is mocked, so the test checks mapping, validation and error format:
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import dev.javahacks.tasks.TaskDtos.CreateTask;
import dev.javahacks.tasks.TaskDtos.TaskView;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
// annotated with @WebMvcTest(TaskController.class); the import package moved in Boot 4, let the IDE add it
class TaskControllerTest {
@Autowired MockMvc mvc;
@MockitoBean TaskService service;
@Test
void createReturns201WithLocation() throws Exception {
when(service.create(any(CreateTask.class))).thenReturn(
new TaskView(7, "Write tests", null, null, TaskStatus.OPEN, Instant.parse("2026-01-01T00:00:00Z")));
mvc.perform(post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Write tests\"}"))
.andExpect(status().isCreated())
.andExpect(header().string("Location", "http://localhost/api/tasks/7"))
.andExpect(jsonPath("$.id").value(7));
}
@Test
void blankTitleIsRejectedWithProblemDetail() throws Exception {
mvc.perform(post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].field").value("title"));
}
@Test
void unknownTaskIsA404() throws Exception {
when(service.get(99)).thenThrow(new TaskNotFoundException(99));
mvc.perform(get("/api/tasks/99")).andExpect(status().isNotFound());
}
}Three layers make a healthy suite: unit tests for business rules in the service, web-layer tests like the one above for the HTTP contract, and a few @SpringBootTest integration tests with a real database through Testcontainers for the wiring, transactions and queries. The contract tests are cheap and catch the regressions clients feel: a renamed field, a changed status, a different error shape.
Mistakes that cost the most time
| Mistake | Effect | Fix |
|---|---|---|
| Returning entities | Lazy-loading errors, infinite recursion, leaked columns | Records as views, mapped in the service |
| No global error handler | Different bodies for different failures, stack traces in responses | One @RestControllerAdvice with ProblemDetail |
200 with an error in the body | Monitoring and caches cannot see failures | Use real status codes |
| Unbounded list endpoints | One request loads the table | Default and maximum page size |
| Accepting the entity as the request body | Clients set id, createdAt, roles | Separate request records |
| Business logic in controllers | Untestable without HTTP | Put rules in services |
| Catching exceptions in each controller | Inconsistent errors | Throw, and handle in the advice |
| Disabling CSRF on a cookie-authenticated API | Cross-site request forgery | Disable only for header-token APIs |
Where this design stops
This is the request-and-response API style, which fits most CRUD-shaped services. If clients need to ask for exactly the fields they want across many resources, GraphQL may fit better; if the callers are internal services that need streaming and strict contracts, look at gRPC. Both trade-offs are laid out in REST against GraphQL and gRPC. Very high-concurrency, I/O-bound services may prefer virtual threads or a reactive stack, which changes how you write handlers but not the contract conventions above. The authoritative references are the Spring MVC reference and RFC 9457 for the error format.


