Response handling is how your API answers a client: the JSON body, the HTTP status code (200, 201, 404 and so on), and the headers. Spring Boot converts a returned Java object into JSON automatically, and ResponseEntity lets you control the status code and headers as well. It is used so clients can tell success from failure by the status code alone, and can read a clear error message in a consistent JSON format. Errors are best handled in one place with @RestControllerAdvice, so controllers stay clean.
Types
- Plain object return: returns the object as JSON with 200 OK.
ResponseEntity<T>: full control of status, headers, and body.@ResponseStatus: fixes a status code on a method or exception class, for example@ResponseStatus(HttpStatus.CREATED).- Common status helpers:
ResponseEntity.ok(),.created(uri),.noContent(),.badRequest(),.notFound(). - Global error handling:
@RestControllerAdvicewith@ExceptionHandlermethods. - Headers:
.header("X-Total-Count", "5"),Location,Content-Type.
