In this article we dive deep into the world of Response Entities in Spring Boot and unravel the mysteries of HTTP Status Codes.
ResponseEntity
The ResponseEntity class is part of the Spring Framework and is commonly used in Spring Boot applications to customize the HTTP response.
It provides methods for setting the response status, headers, and body. You can use it to return different types of data in your controller methods such as JSON, XML or even HTML. You can use generics with ResponseEntity to specify the type of data you are returning.
HTTP Status Code
An HTTP status code is a three digit numeric code returned by a web server as part of the response to an HTTP request made by a client. These status codes are used to convey information about the result or status of the requested operation.
HTTP status codes are grouped into five categories based on their first digit —
1. 1XX (Informational)
These status codes indicate that the request was received and understood, and the server is continuing to process it. These are typically used for informational purposes and rarely seen in practice.
2. 2XX (Successful):
These status codes indicate that the request was successfully received, understood, and processed by the serve.
- 200 OK: The request has been successfully processed, and the server is returning the requested resource.
if(all != null && !all.isEmpty()) {
return new ResponseEntity<>(all, HttpStatus.OK);
}
- 201 Created: The request has been fulfilled, and a new resource has been created as a result.
try {
myEntry.setDate(LocalDateTime.now());
journalEntryService.saveEntry(myEntry);
return new ResponseEntity<>(myEntry, HttpStatus.CREATED);
}
- 204 No Content: The request was successful, but there is no response body (typically used for operations that don't return data, like a successful deletion).
@DeleteMapping("id/{myId}")
public ResponseEntity<?> deleteJournalEntryByID(@PathVariable ObjectId myId) {
journalEntryService.deleteById(myId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
3. 3XX (Redirection)
These status codes indicate that further action is needed to complete the request. They are used when the client needs to take additional steps to access the requested resource.
301 Moved Permanently: The requested resource has been permanently moved to a different URL.
302 Found: The HTTP status code 302 indicates that the requested resource has been temporarily moved to a different URL. When a server sends a response with a 302 status code, it typically includes a location header field that specifies the new temporary URL where the client should redirect to.
304 Not Modified: The client's cached version of the requested resource is still valid, so the server sends this status code to indicate that the client can use its cached copy.
@GetMapping("resource/{myId}")
public ResponseEntity<?> getResourceByID(@PathVariable String myId, HttpServletRequest request) {
// 301 Moved Permanently - Redirecting permanently to a new endpoint
if ("old-resource".equals(myId)) {
return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY)
.header(HttpHeaders.LOCATION, "/new-resource")
.body("301 - Moved Permanently: Resource has a new location.");
}
// 302 Found - Temporary redirect to another endpoint
if ("temp-resource".equals(myId)) {
return ResponseEntity.status(HttpStatus.FOUND)
.header(HttpHeaders.LOCATION, "/temporary-resource")
.body("302 - Found: Temporarily redirected.");
}
// 304 Not Modified - If the resource hasn't changed since the last request
String ifModifiedSince = request.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifModifiedSince != null) {
return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
}
// Returning a sample resource response
String resourceData = "Sample Data for " + myId;
return new ResponseEntity<>(resourceData, HttpStatus.OK);
}
4XX (Client Error)
These status code indicate that there was an error on the client's part, such as malformed request or authentication issues.
400 Bad Request: The server cannot understand or process the client's request due to invalid syntax or other client-side issues.
401 Unauthorized: The client needs to provide authentication credentials to access the requested resource.
403 Forbidden: The client is authenticated, but it does not have permission to access the requested resource.
@DeleteMapping("id/{myId}")
public ResponseEntity<?> deleteJournalEntryByID(@PathVariable ObjectId myId, Principal principal) {
if (myId == null) {
return new ResponseEntity<>("400 - Bad Request: ID is required", HttpStatus.BAD_REQUEST);
}
if (principal == null) {
return new ResponseEntity<>("401 - Unauthorized: Login required", HttpStatus.UNAUTHORIZED);
}
try {
journalEntryService.deleteById(myId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (AccessDeniedException e) {
return new ResponseEntity<>("403 - Forbidden: You don't have permission", HttpStatus.FORBIDDEN);
}
}
5XX (Server Error)
These status codes indicate that there was an error on the server's part while trying to fulfill the request.
500 Internal Server Error: A generic error message indicating that something went wrong on the server, and the server could not handle the request.
502 Bad Gateway: The server acting as a gateway or proxy received an invalid response from an upstream server.
503 Service Unavailable: The server is currently unable to handle the request due to temporary overloading or maintenance.
@GetMapping("service/{serviceId}")
public ResponseEntity<?> getServiceStatus(@PathVariable String serviceId) {
// 500 Internal Server Error - Simulating an unexpected server failure
if ("error-service".equals(serviceId)) {
return new ResponseEntity<>("500 - Internal Server Error: Something went wrong!", HttpStatus.INTERNAL_SERVER_ERROR);
}
// 502 Bad Gateway - Simulating an issue with an upstream service
if ("gateway-issue".equals(serviceId)) {
return new ResponseEntity<>("502 - Bad Gateway: Upstream service is unreachable!", HttpStatus.BAD_GATEWAY);
}
// 503 Service Unavailable - Simulating service downtime
if ("maintenance".equals(serviceId)) {
return new ResponseEntity<>("503 - Service Unavailable: Try again later!", HttpStatus.SERVICE_UNAVAILABLE);
}
return new ResponseEntity<>("Service " + serviceId + " is running smoothly!", HttpStatus.OK);
}
Top comments (0)