Spring Boot is a popular framework for building robust and scalable REST APIs. One of the key features of a REST API is returning proper HTTP status codes to indicate the outcome of an API request. In this blog post, we’ll discuss the importance of HTTP status codes and how to properly return them in a Spring Boot Rest API.



What are HTTP status codes?

HTTP status codes are three-digit codes that indicate the outcome of an HTTP request. They are returned by the server to the client to inform the client about the success or failure of an API request. HTTP status codes are grouped into five classes based on their first digit:

  1. 1xx (Informational): The request was received, and the server is continuing to process it.
  2. 2xx (Successful): The request was successfully received, understood, and accepted.
  3. 3xx (Redirection): Further action must be taken in order to complete the request.
  4. 4xx (Client Error): The request contains bad syntax or cannot be fulfilled by the server.
  5. 5xx (Server Error): The server failed to fulfill a valid request.


Why are HTTP status codes important?

HTTP status codes are important for several reasons:

  1. They provide a clear and concise way to communicate the outcome of an API request.
  2. They allow clients to easily understand the status of an API request and take appropriate action.
  3. They help to standardize the way REST APIs behave, making it easier for clients to integrate with multiple APIs.
  4. They provide additional information to developers for debugging purposes.


Returning HTTP status codes in Spring Boot Rest API

Spring Boot provides several ways to return HTTP status codes in a Rest API. In this section, we’ll discuss the most common ways to return HTTP status codes in a Spring Boot Rest API.



Using ResponseEntity

The most common way to return HTTP status codes in a Spring Boot Rest API is by using the ResponseEntity class. The ResponseEntity class is a type that represents an HTTP response, including status code, headers, and body.

Here is an example of using the ResponseEntity class to return a 201 Created status code:

@RestController
public class ExampleController {

    @PostMapping("/example")
    public ResponseEntity<String> createExample(@RequestBody Example example) {
        // logic to create a new example
        return ResponseEntity.status(HttpStatus.CREATED).body("Example created successfully");
    }
}

In this example, the createExample() method returns a 201 Created status code along with a response body. The HttpStatus.CREATED enum value represents the 201 status code.



Using @ResponseStatus

Another way to return HTTP status codes in a Spring Boot Rest API is by using the @ResponseStatus annotation. The @ResponseStatus annotation is used to set the HTTP status code for a response.

Here is an example of using the @ResponseStatus annotation to return a 400 Bad Request status code:

@RestController
public class ExampleController {

    @PostMapping("/example")
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public void createExample(@RequestBody Example example) {
        // logic to create a new example
        throw new ExampleException("Invalid example data");
    }
}

In this example, the createExample() method returns a 400 Bad Request status code when an ExampleException is thrown. The @ResponseStatus annotation sets the HTTP status code for the response.



Using Exceptions

Exceptions can also be used to return HTTP status codes in a Spring Boot Rest API. By using exceptions, you can map specific exceptions to specific HTTP status codes.

Here is an example of using exceptions to return a 404 Not Found status code:

@RestController
public class ExampleController {

    @GetMapping("/example/{id}")
    public Example getExample(@PathVariable Long id) {
        Example example = exampleRepository.findById(id).orElseThrow(() -> new ExampleNotFoundException(id));
        return example;
    }
}

@ResponseStatus(HttpStatus.NOT_FOUND)
class ExampleNotFoundException extends RuntimeException {
    public ExampleNotFoundException(Long id) {
        super("Example with id " + id + " not found");
    }
}

In this example, the getExample() method uses the orElseThrow() method to throw an ExampleNotFoundException if an example with the given id cannot be found. The ExampleNotFoundException is annotated with @ResponseStatus, which sets the HTTP status code for the response to 404 Not Found.



Conclusion

Returning proper HTTP status codes is an important part of building a REST API. In this blog post, we discussed the importance of HTTP status codes and how to properly return them in a Spring Boot Rest API using the ResponseEntity class, the @ResponseStatus annotation, and exceptions. With the knowledge you’ve gained from this post, you should now be able to properly return HTTP status codes in your Spring Boot Rest API.