Return Custom Status Code from Rest Controller

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

To return a specific HTTP Status code in a Spring Boot RESTful Web Service application, you can use the ResponseEntity class.

ResponseEntity with HTTP Status Code

Let’s assume we have this very simple web service endpoint which needs to update the user details and it needs to respond back to an HTTP Request with a 409 HTTP Status code. The 409 HTTP Status code stands for CONFLICT and can take place when the request could not be processed because of conflict in the current state of the resource, such as an edit conflict between multiple simultaneous updates.

@PutMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity getUser(@RequestBody UserDetailsModel userDetails)
  /* some code here * /

 return new ResponseEntity(HttpStatus.CONFLICT);

ResponseEntity with HTTP Status Code and Body

We can also use ResponseEntity to respond back to an HTTP request and provide both a specific HTTP Status code and an object to be returned in a Response Body.

In the code example below I am returning HTTP Status code 200 OK but it could be another HTTP Status code. You can find a list of possible HTTP Status code here:

@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<UserRest> getUser(@PathVariable String userId)
 UserRest userModel = new UserRest();

 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 checkout 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 *