Spring Boot is a popular framework for building REST APIs due to its ease of use and robust features. One of the key features of REST APIs is the ability to return different HTTP status codes to indicate the outcome of an API request. In this blog post, we’ll explore how to return different HTTP status codes from within a controller method in Spring Boot.
HTTP Status Codes
HTTP status codes are three-digit numbers that indicate the outcome of an API request. They provide a standardized way for a server to communicate the result of a request to the client. Here are some of the most common HTTP status codes:
- 200 OK: The request was successful and the server has returned the requested data.
- 201 Created: The request was successful and a new resource was created on the server.
- 204 No Content: The request was successful but there is no representation to return.
- 400 Bad Request: The request was invalid or cannot be served.
- 401 Unauthorized: The request requires user authentication.
- 403 Forbidden: The request is valid, but the server refuses to respond to it.
- 404 Not Found: The requested resource could not be found on the server.
- 500 Internal Server Error: An error occurred on the server.
Returning HTTP Status Codes with ResponseEntity
The easiest way to return a specific HTTP status code from a controller method is to use the ResponseEntity
class. The ResponseEntity
class represents a response from the server and allows you to specify the status code, headers, and body of the response.
Here’s an example of how to return a 201 Created status code from a controller method:
@PostMapping("/api/resources")
public ResponseEntity<Resource> createResource(@RequestBody Resource resource) {
// Save the resource
Resource savedResource = resourceRepository.save(resource);
// Return the resource with a 201 Created status code
return ResponseEntity.status(HttpStatus.CREATED).body(savedResource);
}
In this example, the @PostMapping
annotation maps the createResource
method to a POST request to the /api/resources
endpoint. The @RequestBody
annotation tells Spring to extract the request body and map it to a Resource
object.
The method saves the resource to the repository and returns a ResponseEntity
with a 201 Created status code and the saved resource as the response body.
Returning HTTP Status Codes with Exception Handling
Another way to return a specific HTTP status code from a controller method is to throw an exception and handle it using an exception handler. This approach is useful when you want to return a specific HTTP status code based on the outcome of some business logic.
Here’s an example of how to return a 401 Unauthorized status code from a controller method using exception handling:
@GetMapping("/api/resources/{id}")
public Resource getResource(@PathVariable Long id) {
Resource resource = resourceRepository.findById(id).orElseThrow(ResourceNotFoundException::new);
if (!resource.isVisibleToUser()) {
throw new UnauthorizedException();
}
return resource;
}
In this example, the @GetMapping
annotation maps the getResource
method to a GET request to the /api/resources/{id}
endpoint. The @PathVariable
annotation tells Spring to extract the id
parameter from the URL and map it to the id
argument in the method.
The method uses the resourceRepository
to find the resource with the specified id
. If the resource is not found, it throws a ResourceNotFoundException
. If the resource is not visible to the user, it throws an UnauthorizedException
.
To handle these exceptions, we can create an exception handler class:
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse("Resource not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<ErrorResponse> handleUnauthorizedException(UnauthorizedException ex) {
ErrorResponse error = new ErrorResponse("Unauthorized");
return new ResponseEntity<>(error, HttpStatus.UNAUTHORIZED);
}
}
In this example, the @ControllerAdvice
annotation indicates that this class is an exception handler for all controllers in the application. The two @ExceptionHandler
methods handle the ResourceNotFoundException
and UnauthorizedException
respectively.
Each method returns a ResponseEntity
with an ErrorResponse
object and the appropriate HTTP status code.
Conclusion
In this blog post, we’ve explored how to return different HTTP status codes from a Spring Boot REST API. We’ve seen two ways to achieve this: using the ResponseEntity
class and using exception handling.
Using the ResponseEntity
class is the simplest way to return a specific HTTP status code and is recommended for most use cases. Using exception handling is useful when you need to return a specific HTTP status code based on the outcome of some business logic.
By returning the appropriate HTTP status code, you can provide valuable information to the client about the outcome of an API request and make your REST API more robust and user-friendly.