by BehindJava

How to return HTTP status codes from Rest Controller in Spring Boot

Home » springboot » How to return HTTP status codes from Rest Controller in Spring Boot

In this tutorial we are going to learn about returning the HTTP status codes from the Rest Controller using ResponseEntity class in Spring Boot.

ResponseEntity is Extension of HTTP Entity that adds an HTTP status code. Used in RestTemplate as well as in @Controller methods.

Now get users method return the ResponseEntity object in which it can have few parameters since it has different constructors, based on this it can take body, status.

In the below code snippet I’m returning HTTP status FOUND.

Sample Code Snippet:

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.behindjava.tutorial.model.UserModel;

@RestController
@RequestMapping("/users")
public class UserController {

	@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
	public ResponseEntity<UserModel> getUser(@PathVariable String userId) {
		UserModel um = new UserModel();
		um.setFirstname("Lakshmi Deepak");
		um.setLastname("Chella");
		um.setUserId("cl001");
		um.setEmail("cldeepak@gmail.com");
		return new ResponseEntity<UserModel>(um, HttpStatus.FOUND);
	}
}

Using postman you can test the get mapping where the following output is shown along with the specified HTTP status code in the Rest Controller.

title

Please refer to HTTP Status Codes tutorial for more information.

Previous                                                                                                               Next