This post will discuss how to return the standard HTTP status code in Spring Boot.

There are several ways to return HTTP status codes in Spring Boot, depending on the scenario and the level of control we want. Here are some of the possible solutions:

1. Using ResponseEntity Class

We can use the ResponseEntity class to wrap our response data and also specify the HTTP status code and headers. This gives us more flexibility and control over the response. For example, we can use the ResponseEntity.ok() method to create a response entity with a 200 (OK) status code and a JSON object as the body as follows:

2. Using @ResponseStatus Annotation

We can use the @ResponseStatus annotation on our controller methods or exception classes to specify the HTTP status code that should be returned for that method or exception. For example, we can use the @ResponseStatus(HttpStatus.CREATED) annotation on a controller method that creates a new resource to indicate a 201 (Created) status code as follows:

3. Using @ControllerAdvice and @ExceptionHandler Annotations

We can use the @ControllerAdvice and @ExceptionHandler annotations to handle exceptions globally and return custom status codes based on the exception type. For example, we can create a class annotated with @ControllerAdvice that defines methods annotated with @ExceptionHandler for different exceptions and use the ResponseEntity class or the @ResponseStatus annotation to set the status code as follows:

That’s all about returning the standard HTTP status code in Spring Boot.