Skip to content
javahacks.dev
Spring MVC

Spring MVC HTTP Status Codes and How to Return Them Right

Return correct HTTP status codes from Spring MVC with ResponseStatus, ResponseEntity, ResponseStatusException and handlers, and know which fits.

5 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Spring, Swagger and Spring Boot logos.

Clients, proxies, caches and monitoring read the status code before anything else, and most of them never parse the body. A controller that answers 200 for every outcome makes all of them blind: the retry logic does not retry, the load balancer keeps sending traffic to a broken instance, and the dashboard that counts errors shows zero while users see failures. This post covers the three ways Spring MVC lets you set the status, and how to choose between them. It targets Spring Framework 7.

The fixed case: @ResponseStatus

java
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
Order create(@Valid @RequestBody NewOrder request) { return service.create(request); }

@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
void delete(@PathVariable long id) { service.delete(id); }

The annotation sets the status for a successful return, and Spring changes nothing else. Use it when the answer never varies. It has two limits. It cannot add a Location header, which a 201 should carry, and it cannot choose at runtime. If the method throws, the annotation is not consulted at all, since the exception path decides the status instead.

The dynamic case: ResponseEntity

java
@GetMapping("/{id}")
ResponseEntity<Order> get(@PathVariable long id) {
    return service.find(id)
            .map(ResponseEntity::ok)
            .orElseGet(() -> ResponseEntity.notFound().build());
}

@PostMapping
ResponseEntity<Order> create(@Valid @RequestBody NewOrder request) {
    Order order = service.create(request);
    return ResponseEntity.created(URI.create("/orders/" + order.id())).body(order);
}

ResponseEntity carries the status, the headers and the body together, so a 201 with its Location is one expression. The cost is a return type that is no longer the domain type, which makes the method signature noisier and the generated API documentation less direct. The patterns are collected in using ResponseEntity properly. We use it for creations and conditional reads, and @ResponseStatus for the plain cases.

Throwing a status

java
Order order = service.find(id)
        .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "order " + id));

This keeps controller bodies short, and it works from any layer called during a request, which ResponseEntity cannot. The trade-off is that a web concept now lives in the service. If the service is also called from a batch job, a ResponseStatusException has no meaning there, and a domain exception is cleaner: define OrderNotFoundException, throw it from the service and translate it at the web boundary.

java
@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(OutOfStockException.class)
    ProblemDetail outOfStock(OutOfStockException e) {
        ProblemDetail p = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
        p.setTitle("Out of stock");
        return p;
    }
}

ProblemDetail is Spring's representation of RFC 9457, the standard error body, and it is described in designing error responses. One advice class gives every endpoint the same error shape and the same status for the same condition, which is the main thing a client developer wants from you.

Which code for which outcome

OutcomeCode
Read succeeded200
Created, with Location201
Accepted for later work202
Done, nothing to return204
Malformed or invalid input400
Not signed in401
Signed in but not allowed403
No such resource404
Wrong verb for the path405
State conflict, duplicate409
Valid syntax, failed business rule422
Server bug500

The 401 and 403 pair is the regular confusion: 401 means the caller is not identified and 403 means "I know, and the answer is no". See 401 Unauthorized and 403 Forbidden. For retries of a creation, see idempotent endpoints.

We think the 400 versus 422 line is where teams waste the most meeting time, and our rule is short: 400 when the request could not be understood (broken JSON, wrong type), 422 when it parsed fine and a rule rejected it (a past delivery date). If you use Bean Validation, the failures are 400 by Spring's default, and either choice is defensible as long as the whole API agrees and says so in its documentation.

A 204 must have no body, and a 404 on a DELETE of something already gone is a design question. Many APIs answer 204 for an idempotent delete, so a retry looks the same as the first call.

Be consistent across the API

Pick one way per kind of outcome and write it down. Clients write their error handling once, so a 404 that sometimes carries a body and sometimes does not, or a duplicate that is 400 in one resource and 409 in another, forces every consumer to special-case you. A shared advice class, a table like the one above and one test per status keep behavior from drifting as endpoints are added by different people. The test is cheap: MockMvc performs the request and asserts status().isConflict() and the body fields.

Statuses Spring produces on its own

The framework generates many without your code: 400 for binding and type mismatch failures, 404 when no handler matches, 405 for a wrong method, and 406 and 415 for media type problems. Their default bodies differ from your ProblemDetail, so a client sees two error shapes in one API. Extend ResponseEntityExceptionHandler in a @RestControllerAdvice to render all of them in one format, and enable spring.mvc.problemdetails.enabled=true if you want Spring's RFC 9457 bodies without writing the class.

Testing the status contract

Status codes are cheap to assert and expensive to get wrong, so give each documented outcome a MockMvc test. One class per resource is enough:

java
@Test
void createReturns201WithLocation() throws Exception {
    mvc.perform(post("/orders").contentType(APPLICATION_JSON).content("{\"sku\":\"A1\",\"qty\":2}"))
       .andExpect(status().isCreated())
       .andExpect(header().string("Location", matchesPattern(".*/orders/\\d+")));
}

@Test
void unknownOrderReturns404() throws Exception {
    mvc.perform(get("/orders/999999")).andExpect(status().isNotFound());
}

Add the negative cases that produce 400, 409 and 422, and one for an unexpected exception that must come back as a 500 with the standard error body and no stack trace in it. The leak of an exception message is a common finding in security reviews, and the fix is the advice class returning a generic detail for any exception it does not recognize.

Caching and the status code

A correct status also drives caching. A GET that answers 200 is cacheable by default rules unless you say otherwise, and a 404 may be cached by a CDN for a short time, which matters when a resource is created a moment after a client asked for it. A 201 or a 204 on a POST is never cached. If you return 304 for a conditional request, send it with no body and keep the ETag. Setting Cache-Control: no-store on authenticated responses is a separate decision that the status code does not make for you, and forgetting it is how a shared proxy ends up serving one user's data to another.

Where this does not apply

Do not answer 200 with {"error": ...} as a style. It breaks retries, caches, circuit breakers and any dashboard that counts failures, and it is the usual cause of an outage that nobody was paged for. WebSocket and server-sent event endpoints have their own conventions, since the status is fixed once the stream has started. The semantics of each code are defined in RFC 9110, and the Spring side is in Return Values.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.