Return Custom HTTP Status from Spring Controller

In this tutorial, you will learn how to make a method in your Rest Controller class return a custom HTTP status code.

To return a specific HTTP status code from a Spring Controller method in your application, you can use the ResponseEntity class.

ResponseEntity with HTTP Status Code

Let’s assume we have a simple web service endpoint that needs to respond with a 409 HTTP Status code. The 409 HTTP Status code stands for CONFLICT and can occur when the request cannot be processed because of a conflict in the current state of the resource, such as an edit conflict between multiple simultaneous updates.

To make our API endpoint respond with HTTP status code 409 CONFLICT, it will return ResponseEntity(HttpStatus.CONFLICT);

@PutMapping(path = "/{userId}")
public ResponseEntity getUser(@RequestBody UserDetailsModel userDetails)
{
  /* some code here * /

 return new ResponseEntity(HttpStatus.CONFLICT);
}

To learn how to test that your API Endpoint returns the correct HTTP Status code, check the following tutorial Validating HTTP Status Code with REST Assured.

ResponseEntity with HTTP Status Code and Response Body

We can also use ResponseEntity to respond back to an HTTP request and provide both HTTP Status code and Response Body.

In the code example below, I am returning HTTP Status code 200 OK. If needed, it could be another HTTP Status code. You can find a list of possible HTTP Status codes here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

@GetMapping(path = "/{userId}")
public ResponseEntity<UserRest> getUser(@PathVariable String userId)
{
 UserRest userModel = new UserRest();
 userModel.setFirstName("Sergey");
 userModel.setLastName("Kargopolov");

 return ResponseEntity.status(HttpStatus.OK).body(userModel);
}

Video Tutorial

I hope this short tutorial was helpful for you. For more tutorials and video examples on how to build RESTful Web Services with Spring Boot, check out this page RESTful Web Services with Spring Boot.

You can also check the below list of video courses on Spring Boot and Spring MVC because one of them might greatly help you increase your learning progress.


Leave a Reply

Your email address will not be published. Required fields are marked *