Status codes
A status code is the three-digit number at the start of every HTTP response that tells the client what happened. 200 means it worked, 404 means the thing does not exist, 500 means the server broke.
Detailed Explanation
The status code is the one part of a response that every client understands without reading your documentation. Browsers, load balancers, CDNs, retry libraries and monitoring dashboards all make decisions from it. Your JSON error message is for humans; the status code is for machines.
The first digit gives the category, and memorising the five categories is worth more than memorising individual numbers.
| Class | Meaning | Who is responsible |
|---|---|---|
1xx | Informational, keep going | protocol level, rarely seen in application code |
2xx | Success | nobody, it worked |
3xx | Redirect, look elsewhere | client should follow |
4xx | The request was wrong | the caller |
5xx | The server failed a valid request | you |
That 4xx versus 5xx split is the whole point of the design. 4xx means retrying the identical request is pointless because the caller must change something. 5xx means the request was reasonable and retrying later may succeed. Client retry logic, circuit breakers and your on-call alerting all hang off that distinction, which is why mislabelling matters.
The codes that carry real work in a Java API are a short list. 200 OK for a successful read. 201 Created with a Location header for a successful create. 204 No Content for a successful delete or an update with nothing to return. 400 Bad Request for malformed or invalid input. 401 Unauthorized when there is no valid credential, versus 403 Forbidden when the credential is valid but lacks permission — the names are historically backwards, and interviewers like asking. 404 Not Found for a missing resource. 409 Conflict for a state clash, such as cancelling an order that already shipped. 415 Unsupported Media Type when the Content-Type is missing or wrong. 422 Unprocessable Entity for syntactically valid JSON that fails business rules. 429 Too Many Requests for rate limiting. 500 for an unhandled exception, and 503 Service Unavailable when a dependency is down.
In Java the raw constants live in jakarta.servlet.http.HttpServletResponse (SC_NOT_FOUND and friends) and you set them with response.setStatus(...). Spring gives you better options. Return a ResponseEntity when the code varies per call. Put @ResponseStatus on a custom exception when one exception always maps to one code. Use @ExceptionHandler inside a @RestControllerAdvice class to translate exceptions centrally, so controllers stay free of error plumbing.
Spring Boot 3 ships ProblemDetail, its implementation of RFC 7807. It standardises the error body with type, title, status, detail and instance fields, so clients stop parsing a different error shape from every service. It costs you nothing but an import and gives callers something predictable.
The cost of getting codes wrong is not CPU, it is operational blindness. Return 200 with {"error": "..."} inside and your dashboards show a perfectly healthy service while users see failures, no retry policy fires, and no alert triggers. Return 500 for invalid user input and you page an engineer at 3am for a typo in someone's form.
Code Examples
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
// This exception always means the same thing, so bind it to a code once.
@ResponseStatus(HttpStatus.CONFLICT) // every throw becomes 409
class OrderAlreadyShippedException extends RuntimeException {
OrderAlreadyShippedException(long id) {
super("Order " + id + " has already shipped");
}
}
// @RestControllerAdvice applies these handlers to every controller in the application.
@RestControllerAdvice
public class ApiErrorHandler {
// ProblemDetail is Spring Boot 3's RFC 7807 error body. Media type is application/problem+json.
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail notFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
// Returning the ProblemDetail itself sets the response status to 404 for us.
return problem;
}
// Thrown by @Valid when a constraint like @Min(1) fails. The caller sent bad data: 400, not 500.
@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<ProblemDetail> invalid(MethodArgumentNotValidException ex) {
ProblemDetail problem = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
problem.setTitle("Validation failed");
problem.setDetail(ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + " " + e.getDefaultMessage())
.reduce((a, b) -> a + "; " + b)
.orElse("invalid request"));
return ResponseEntity.badRequest().body(problem);
}
}package com.example.orders;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.time.Duration;
@RestController
@RequestMapping("/v1/reports")
public class ReportController {
private final ReportService service;
public ReportController(ReportService service) {
this.service = service;
}
@PostMapping
public ResponseEntity<Void> request(@RequestBody ReportRequest body) {
String id = service.enqueue(body);
// The report is not built yet, so 201 would be a lie. 202 means "accepted, still working".
return ResponseEntity.accepted()
.location(URI.create("/v1/reports/" + id)) // poll here for progress
.build();
}
@GetMapping("/quota")
public ResponseEntity<String> quota() {
if (service.overQuota()) {
// 429 plus Retry-After: well-behaved clients back off for exactly this long.
return ResponseEntity.status(429)
.header(HttpHeaders.RETRY_AFTER, String.valueOf(Duration.ofMinutes(5).toSeconds()))
.body("quota exceeded");
}
return ResponseEntity.ok("within quota");
}
}Common Gotchas
`200 OK` with an error inside the body
the response says success, so retry libraries do not retry, caches may store the failure, and your error-rate metric stays flat while users are broken. If the operation failed, the status code must say so.
`500` for bad user input
an unhandled `NumberFormatException` from parsing a query parameter surfaces as `500`, which tells the caller to retry an identical request that can never work, and wakes up whoever owns the service. Catch it and answer `400`.
Choosing `403` when you mean `401`
`401` means "I do not know who you are", and must come with a `WWW-Authenticate` header, which is the client's signal to refresh a token or show a login screen. `403` means "I know who you are and the answer is still no". Sending `403` for an expired token leaves clients stuck without a way to recover.
`404` is a legitimate answer to a hidden resource
returning `404` instead of `403` for a record the caller may not see is deliberate, because `403` confirms the record exists. That leak matters for resources keyed by a guessable id.