The 30 second answer
By default a successful method returns 200. When I need a different status or headers, I return ResponseEntity, for example ResponseEntity.created with a Location header for 201, or noContent for 204. @ResponseStatus on a method sets a fixed status. For errors I throw an exception and map it to 404, 400 or 409 in a @RestControllerAdvice, so controllers stay clean.
<!-- level: 1 --> <!-- must_know: true -->
- Default: a method that returns normally gives
200 OK. - **
ResponseEntity:** full control of status, headers and body.ResponseEntity.ok(body),ResponseEntity.created(location).body(dto)for201 Created,ResponseEntity.noContent().build()for204,ResponseEntity.status(HttpStatus.ACCEPTED)for202. - **
@ResponseStatus(HttpStatus.CREATED)** on the method: a fixed status without wrapping the return value. - Errors: throw a domain exception such as
OrderNotFoundExceptionand map it centrally to404(see the next question).ResponseStatusExceptionlets you throw a status directly when you don't want a custom exception.
Status codes to know cold: 200 OK, 201 Created, 204 No Content, 400 Bad Request (invalid input), 401 Unauthorized (not authenticated), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict, 422 Unprocessable Content, 500 Internal Server Error, 503 Service Unavailable. The general HTTP rules are in Which HTTP methods are safe or idempotent, and how do status codes and caching fit?.
Sources (1)
- Spring Framework: ResponseEntitydocs.spring.io