Using ResponseEntity in Spring

You are currently viewing Using ResponseEntity in Spring
ResponseEntity & RequestEntity parts
  • Post category:Spring boot

ResponseEntity, RequestEntity are used in Spring REST apis, RequestEntity is used as method level argument and ResponseEntity is used as method response. Both of these, can wrap any type of bean as HTTP body and provides out of the box features. In this article, we will discuss about the ResponseEntity & RequestEntity, implementations and examples.

ResponseEntity and RequestEntity both are the extensions of HttpEntity. ResponseEntity represents an HTTP response including status, headers and body, whereas RequestEntity wraps the request inside it and exposes the additional information of HTTP method and the target url.

What is ResponseEntity?

ResponseEntity is an extension of HttpEntity that represents an HTTP response including status, headers and body. ResponseEntity allows you to modify the response with optional headers and status code. 

In spring applications, ResponseEntity is used in @Controller methods as well as in RestTemplate. ResponseEntity class is present in the http package. The parameter T in org.springframework.http.ResponseEntity<T> represents body type.

Why is ResponseEntity used?

ResponseEntity represents the entire HTTP response. You have more control over response by including body, headers and status code.

As a good programming practice, it’s always required that server response should contain accurate headers and status code. Without ResponseEntity, you can control the response body but it will be hard to control the headers and status code.

When to use ResponseEntity?

ResponseEntity is used when you need to change HTTP headers or HTTP status code based upon your business logic or incoming request. ResponseEntity wraps the original object as its body which is optional. 

If you want to return an object or null, ResponseEntity will work in either way. For null objects, you may have to set the HTTP status like not found or no content. ResponseEntity provides the flexibility to dynamically set HTTP headers as well as custom HTTP headers.

What is RequestEntity in Spring?

RequestEntity is an extension of HttpEntity that exposes the information of HTTP method and uri. RequestEntity is used in the RestTemplate to prepare outgoing requests and in @Controller methods as request input. 

RequestEntity is present in the http package. The parameter T in org.springframework.http.RequestEntity<T> represents body type. 

RequestEntity helps in fetching the additional details for incoming requests like HTTP headers, HTTP method, request url, body and request entity type. If you need these additional details then you use RequestEntity.

RequestEntity example in spring

In the Spring application, create a REST api method with HTTP POST method. Wrap the input bean inside RequestEntity at method parameters level. Inside the method, you can access the RequestEntity object to fetch HTTP headers, HTTP method, url, request type and request body. 

In the following example, we have an input bean as “Student” which is wrapped inside RequestEntity. Inside the method we are just logging the entire information present inside RequestEntity and returning the incoming request object as response.

@PostMapping("/example/request")
public ResponseEntity<Student> requestEntityExample(RequestEntity<Student> requestEntity) {
  log.info("RequestEntity Headers {}", requestEntity.getHeaders());
  log.info("RequestEntity method {}", requestEntity.getMethod());
  log.info("RequestEntity URL {}", requestEntity.getUrl());
  log.info("RequestEntity Type {}", requestEntity.getType());
  log.info("RequestEntity body {}", requestEntity.getBody());

  return ResponseEntity.ok(requestEntity.getBody());

How to use ResponseEntity?

ResponseEntity can be initialized in two ways, either using ResponseEntity builder or ResponseEntity constructors. Although both ways are different, the underlying processing part remains the same. To reduce boilerplate code, builder is a more preferred way.

ResponseEntity Builder

ResponseEntity provides an inbuilt builder, which provides a handy way to create ResponseEntity objects with less code line. ResponseEntity.BodyBuilder defines a builder which helps in adding the content to the response and extends ResponseEntity.HeadersBuilder<ResponseEntity.BodyBuilder

ResponseEntity Constructors

ResponseEntity constructors usage is a traditional way where we can create objects using the “new” keyword. There are 4 predefined constructors for ResponseEntity.

ResponseEntity Constructors TypesResponseEntity Constructors Purpose and Example
ResponseEntity(HttpStatus status)Creates a new ResponseEntity with the given status code only, without any headers and body.Example: new ResponseEntity(HttpStatus.OK);
ResponseEntity(MultiValueMap<String,String> headers, HttpStatus status)Creates a new HttpEntity with the given headers and status code and without any body content.Example: new ResponseEntity(responseHeaders, HttpStatus.NO_CONTENT);
ResponseEntity(T body, HttpStatus status)Creates a new ResponseEntity with the given body and status code, and without any headers.Example: new ResponseEntity(“Constructor example”, HttpStatus.NO_CONTENT);
ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus status)Creates a new HttpEntity with the given headers, body and status codeExample: new ResponseEntity(“Constructor example”, responseHeaders, HttpStatus.NO_CONTENT);
ResponseEntity Constructors

ResponseEntity Examples

Lets see different usage of ResponseEntity with different examples:

ResponseEntity add custom headers

ResponseEntity provides an option to set custom headers in response. To add custom headers, you need to create an object of HttpHeaders bean and then you set any number of headers into your response.

In the following example, we are setting one custom header named “technicalsand-Example-Header” into response, with value “https://technicalsand.com”.

@GetMapping("/example/headers")
public ResponseEntity exampleHeaders() {
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.set("technicalsand-Example-Header", "https://technicalsand.com");
  return ResponseEntity.ok("success",).headers(responseHeaders).build();
}

ResponseEntity custom headers output

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/headers”. Like in the following image, you will be able to see the customer header as part of response headers.

ResponseEntity headers example
ResponseEntity headers example

ResponseEntity example to return empty response

ResponseEntity can be used to return an empty response, you can leave the response body null or you can use noContent() method to mention that there is no body associated.

In the following example, We have just returned one ResponseEntity object with noContent option.

@GetMapping("/example/empty")
public ResponseEntity empty() {
  return ResponseEntity.noContent().build();
}

Sometimes based upon request processing, we need to either send body content and sometimes not. In the following example, you can see that based upon the boolean flag we are returning body content otherwise not.

@GetMapping("/example/optional/empty")
public ResponseEntity<List<String>> emptyOptional(@RequestParam(required = false) boolean fillData) {
  if (fillData) {
     List<String> data = Collections.singletonList("Sample Data");
     return ResponseEntity.ok(data);
  }
  return ResponseEntity.noContent().build();
}

ResponseEntity empty response output

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/empty”. Like in the following image, you will see that no response is returned, only the HTTP status and default response headers are present.

ResponseEntity Empty Response Example
ResponseEntity Empty Response Example

ResponseEntity example to return String 

ResponseEntity body content can be any data type. In case of String, you can just set ResponseEntity’s body with String value.

In the following example, we are using a shortcut for ResponseEntity to set body content as String and HTTP status as Ok (200).

@GetMapping("/example/string")
public ResponseEntity<String> exampleString() {
  return ResponseEntity.ok("String example here");
}

ResponseEntity String response output

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/string”. Like in the following image, you will see that a String is returned as a response body.

ResponseEntity String example
ResponseEntity String example

ResponseEntity example to return JSON

ResponseEntity can return any object as JSON automatically using Jackson library internally. You all need to set the ResponseEntity’s body with an object (of any type). ResponseEntity on returning the HTTP response, converts this object to JSON. No specific conversion is required for JSON output.

In the following example, we have one object of Student class and setting it as the body of ResponseEntity.

@GetMapping("/example/json")
public ResponseEntity<Student> exampleJson() {
  Student student = Student.builder().rollNo(10).name("Student1").className("first").build();
  return ResponseEntity.ok(student);
}

ResponseEntity JSON response output

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/json”. Like in the following image, you will see that a JSON response is received and the object is automatically converted to JSON.

ResponseEntity json example
ResponseEntity json example

ResponseEntity example to return list of objects

ResponseEntity can return a list of objects or a single object. A list of objects will be converted to JSON Array output by ResponseEntity.

In the following example, We have a list of students and which is directly used as the body in ResponseEntity.

@GetMapping("/example/list")
public ResponseEntity<List<Student>> exampleList() {
  Student student1 = Student.builder().rollNo(10).name("Student1").className("first").build();
  Student student2 = Student.builder().rollNo(11).name("Student2").className("first").build();
  List<Student> students = List.of(student1, student2);
  return ResponseEntity.ok(students);
}

ResponseEntity list of object response output

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/list”. Like in the following image, you will see that a JSON response is received which contains the list of objects in the form of JSON.

ResponseEntity list example
ResponseEntity list example

ResponseEntity example to return only status

ResponseEntity provides options to set only status without body and headers. HTTP status can be added in ResponseEntity ignoring body content and headers.In the following example, we want to set HTTP status as NOT_ACCEPTABLE(406, “Not Acceptable”) , so in ResponseEntity under status method we can adding it.

@GetMapping("/example/status")
public ResponseEntity exampleOnlyStatus() {
  return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).build();
}

Open the browser, open the network tab in developer tools and enter the url “http://127.0.0.1:8080/example/status”. Like in the following image, you will see only HTTP status is returned.

ResponseEntity only status example
ResponseEntity only status example

ResponseEntity example to return stream

ResponseEntity supports all available streaming APIs, that means streaming apis can be wrapped in ResponseEntity to send additional information like content length, chunk size, byte range etc.

In the following example, we want to return a stream response where we will stream a plain text. For simulating the continuous streaming, we have used a for loop here to write the content on an outgoing stream.

@GetMapping("/example/stream")
public ResponseEntity<StreamingResponseBody> exampleStream() {
  StreamingResponseBody streamingResponseBody = outputStream -> {
     for (int i = 1; i <= 100000; i++) {
        outputStream.write(("Data stream line - " + i + "\n").getBytes());
     }
  };
  return ResponseEntity.ok()
        .contentType(MediaType.TEXT_PLAIN)
        .body(streamingResponseBody);
}

ResponseEntity example to return csv 

ResponseEntity supports downloading different file formats like csv, pdf, excel etc. Apart from downloading streamed response is also supported by ResponseEntity, to write on this files directly on client-side at the time of downloading.

In the following example, we want to download a csv containing students’ information. In the body part, we have mentioned StreamingResponseBody which will be used to write the content on downloading files in the browser.

@GetMapping("/example/csv")
public ResponseEntity<StreamingResponseBody> exampleCsv() {
  StreamingResponseBody stream = output -> {
     Writer writer = new BufferedWriter(new OutputStreamWriter(output));
     writer.write("name,rollNo,class" + "\n");
     for (int i = 1; i <= 10000; i++) {
        Student st = Student.builder().rollNo(i).name("Student" + i).className("second").build();
        writer.write(st.getName() + "," + st.getRollNo() + "," + st.getClassName() + "\n");
        writer.flush();
     }
  };
  return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=students.csv")
        .contentType(MediaType.TEXT_PLAIN)
        .body(stream);
}

ResponseEntity and RequestEntity examples Source code

All the examples discussed regarding ResponseEntity and RequestEntity are present in the git repository. You can download the source code from git repository here.

Conclusion

It is a good idea to use ResponseEntity and RequestEntity at maximum extent in spring application. It not only provides the easier ways to use but also standardized your all apis.