Return Custom Status Code from Rest Controller

In this Spring MVC 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 MVC 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<UserRest> getUser(@RequestBody UserDetailsModel userDetails)
{
  /* some code here * /

 return ResponseEntity.status(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: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
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 and Spring MVC checkout this page RESTful Web Services with Spring MVC.

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.