The @ResponseStatus annotation in Spring is the powerful tool used in the building RESTful web services. It is allowed developers to control HTTP (Hypertext Transfer Protocol) status code returned by the application's endpoints or when specific exceptions are thrown. By annotating methods or exception classes, we can clearly communicate with the result of the operation to the clients, whether it is the successful response (200 OK), not found error (404 Not Found), or any other status code defined by HTTP standard.
Why Use @ResponseStatus?
In RESTful APIs, returning the correct HTTP status code is essential for effective communication between the server and the client. The @ResponseStatus annotation simplifies this process by allowing developers to easily link specific status codes to methods or exceptions. This ensures that clients receive the appropriate response for each request.
Prerequisites:
The following are the prerequisites to work with @ResponseStatus annotation in Spring:
- Basic Knowledge of Java and Spring Framework
- Understanding of HTTP Protocol
- Spring Boot or Spring MVC Setup
The above prerequisites will be help the effectively use @ResponseStatus annotation to control HTTP responses in Spring applications.
Implementation of using @ResponseStatus annotation in a Spring Boot application
Step 1 : Create a Spring Boot Project
Refer this article to know how to create a spring boot project.
Step 2: Define the Resource Controller
Create a controller that provides an endpoint to fetch resources. If the resource is not found, the controller will throw a custom exception annotated with @ResponseStatus.
package com.example.demo.controller;
import com.example.demo.exception.ResourceNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/resources")
public class ResourceController {
// Simulated data store for the sake of the example
private static final Map<Integer, String> resources = new HashMap<>();
static {
resources.put(1, "Resource 1");
resources.put(2, "Resource 2");
resources.put(3, "Resource 3");
}
// Endpoint to fetch a resource by ID
@GetMapping("/{id}")
public String getResourceById(@PathVariable int id) {
String resource = resources.get(id);
// If the resource is not found, throw a custom exception
if (resource == null) {
throw new ResourceNotFoundException("Resource with ID " + id + " not found.");
}
return resource;
}
}
Explanation:
- @RestController is annotation which is indicate the class is a REST controller, which is return the data directly instead of the rendering views.
- @RequestMapping (/api/resources) is set the base path for all the endpoints in the controller.
- @GetMapping (/{id}) is annotation maps HTTP GET requests to getResourceById method with {id} representing resource ID in URL.
- resources is a simple Map to simulate the data store of the resources.
- getResourceById method is fetch the resource by its ID. If the resource is not found, it will throw the ResourceNotFoundException.
Step 3: Create a Custom Exception Class
Define a custom exception class that will be used when a resource is not found.
package com.example.demo.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// Custom exception class for handling resource not found scenario
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource Not Found")
public class ResourceNotFoundException extends RuntimeException {
// Constructor that accepts a custom error message
public ResourceNotFoundException(String message) {
super(message);
}
}
Explanation:
- @ReponseStatus (HttpStatus.NOT_FOUND) is the annotation which is used to set the HTTP status code to 404 Not Found whenever the exception is thrown.
- ResourceNotFoundException class is the custom exception that is extends the RuntimeException. The @ResponseStatus annotation is applied to the class, so that when the exception is thrown, the client is receives a 404 Not Found response with reason Resource Not Found.
Step 4: Testing the API
Now, we can run the Spring Boot application and test the API using tools such as Postman or cURL.
1. Fetching an Existing Resource:
Endpoint: GET /api/resources/1Output:
The above response is indicate the resource with ID 1 was successfully found and returned with the 200 OK status.
2. Fetching a Non-Existent Resource:
Endpoint: GET /api/resources/10Output:
The above response is indicate that resource with ID 10 was not found, and the server returned a 404 Not Found status.