Spring ResponseEntity, ResponseBody, ResonseStatus

ResponseEntity represents an HTTP response, including headers, body, and status in a spring restful API. While @ResponseBody puts the return value into the body of the response of API, ResponseEntity also allows us to add headers and status code as well.

Prerequisite :

Let’s take a Java Entity Model Class called “Dependant” to be used in this example.

@Entity
@Table(name = "Dependant")
public class Dependant implements Serializable {

    @Id
    private int deptid;

    @Column(name="firstname")
    private String firstname;

    @Column(name="lastname")
    private String lastname;

    // getter, setter methods ...
}

1. ResponseEntity

Example

Let’s create a simple REST API which returns Dependant class object which we made above, wrapped inside the ResponseEntity.

@GetMapping("/dependant/id/{id}")
public ResponseEntity<Dependant> getDependantbyId(@PathVariable int id){
        
    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
   
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo - Department");

    return ResponseEntity.status(HttpStatus.OK).headers(headers).body(dept);
}

We give ResponseEntity a custom status code, headers, and a body.

OUTPUT

Status : 200 OK

Custom-Header →foo - Department
Content-Type →application/json;charset=UTF-8
Transfer-Encoding →chunked
Date →Tue, 25 Feb 2020 07:48:58 GMT

and body as shown below

{
    "deptid": 1,
    "firstname": "Donald",
    "lastname": "T",
}

2. @ResponseBody

Example

In this example we try to achieve the same as as ResponseEntity but @ResponseBody only returns the body, in this case only the Dependant class object.

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependant2byId(@PathVariable int id){

    Dependant dept = new Dependant();
    dept = dependantRepository.findBydeptid(id);
    
    return dept;
}

With @ResponseBody, only the body is returned. The headers and status code are provided by Spring.

3. @ResponseStatus

@ResponseStatus marks a method or exception class with the status code and reason message that should be returned. The status code is applied to the HTTP response when the handler method is invoked, or whenever the specified exception is thrown.
It overrides status information set by other means, like ResponseEntity or redirect.

Example : Custom Exceptions

@GetMapping("/dependant/id/{id}")
@ResponseBody
public Dependant getDependantbyId(@PathVariable int id){

	if(id>10){
		throw new MyCustomException("the id is not in range");
	}
	Dependant dept = new Dependant();
	dept = dependantRepository.findBydeptid(id);

	return dept;
}
	
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "No such dependant with this id")
public class MyCustomException extends RuntimeException {

    public MyCustomException(String message){
        super(message);
    }
}

Summary

In this article, we looked into ResponseEntity, ResponseBody and ResponseStatus functionalities/annotations. We learnt it by simple examples.
Please let us know if you have any questions or concerns related to the topic in the comments section below.
Hope you liked it !


Difference between @Controller and @RestController annotation

Spring’s @Controller and @RestController Annotations

Controller : In Spring the incoming request are handled by the controllers, in terms of a web based application it is the servlet which is responsible for identifying a correct controller url.

S.No@Controller@RestController
1Typically used in spring mvc applicationsTypically Used in RESTful Web Services/AJAX calls which demand response in specific format like(eg: json, xml).
2It is just @Controller , response body need to be added explicitly.It is a combination of @Controller + @ResponseBody,
It does the job in single statement.
3It typically sends data to a view resolver in html format and is used with technologies like the JSP or FTL.
To send response to REST based or AJAX calls @ResponseBody annotation is used along with @Controller.
It typically sends data back to applications like REST based or AJAX calls which is actually looking for a JSON type response and does not rely on view resolvers.
In such cases use @RestController
4If you see the code within.

@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Component public @interface Controller { //….. }
If you see the code within.

@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { //….. }

Examples

1. @Controller – Usage in spring mvc application

@Controller
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public Department getDepartmentByName(@PathVariable String name, Model model) {
  
        //pull data, set in model and then return the template
  
        return departmentTemplate;
    }
}        
        

2. @Controller + @ResponseBody in spring

@Controller
@ResponseBody
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, 
                    produces ="application/json")
    public Department getDepartmentByName(@PathVariable String name) {
  
        //pull data, set model and then return Object model in json format
  
        return department;
    }
}
        

3. @RestController in spring

@RestController
@RequestMapping("department")
public class DepartmentController
{
    @RequestMapping(value = "/{name}", method = RequestMethod.GET, 
                    produces ="application/json")
    public Department getDepartmentByName(@PathVariable String name) {
  
        //pull data, set model and then return Object model in json format
  
        return department;
    }
}                
        

This code does the same job as in example 2 , here we use single annotation(@RestController) instead of two(@Controller, @ResponseBody).

Spring’s @RequestMapping annotation

This annotation is used to provide routing information or you can understand in a simple way it allows application to understand different apis with the help of URL, a unique URL for every api.

A sample code is here:

@RestController  
public class HomeController {  
@RequestMapping(value = "/allDepartmentNames", method = "GET")  

    public List getAllDepartmentName(){  
  //….
        return list;  
    }  
}                
        

Summary

In this spring boot annotations tutorial you have learnt about annotations and auto configuration features of spring boot. These are few of the most in use annotations which you might surely use in your spring boot application. Hope you liked it !