This project demonstrates how to use ResponseEntity in a Spring Boot application to return various HTTP status codes based on different scenarios, such as OK, Created, Bad Request, Not Found, and No Content.
The ResponseEntity class in Spring Boot provides the flexibility to define both the response body and the HTTP status code. Below are common response scenarios implemented in this project:
-
404 Not Found: When a requested resource is not available, the server returns
HttpStatus.NOT_FOUND.return new ResponseEntity<>(HttpStatus.NOT_FOUND);
Example:
GET /api/entries/{id} Response: 404 Not Found -
201 Created: When a new resource is created, the server returns
HttpStatus.CREATEDalong with the created resource.return new ResponseEntity<>(myEntry, HttpStatus.CREATED);
Example:
POST /api/entries Response: 201 Created
-
400 Bad Request: When invalid data is submitted, the server returns
HttpStatus.BAD_REQUEST.return new ResponseEntity<>(myEntry, HttpStatus.BAD_REQUEST);
Example:
POST /api/entries (invalid data) Response: 400 Bad Request
-
200 OK: When the requested resource is successfully retrieved, the server returns
HttpStatus.OK.return new ResponseEntity<>(journalEntry.get(), HttpStatus.OK);
Example:
GET /api/entries/{id} Response: 200 OK -
204 No Content: When a resource is successfully deleted, the server returns
HttpStatus.NO_CONTENT.return new ResponseEntity<>(HttpStatus.NO_CONTENT);
Example:
DELETE /api/entries/{id} Response: 204 No Content