Home > Enterprise >  How should we send the Spring rest Contoller response in batches if the response is large
How should we send the Spring rest Contoller response in batches if the response is large

Time:12-19

I am trying to send a bulk of Employee data to a client on a daily basis, but unaware how much the volume would be. Thus thinking to send the data in batches. What is the best way to do that in a Spring based project.

 @GetMapping(value = "/employees")
 public List<Employee> findAllEmployees(){
 return employeeService.getAllEmployees();
 }

I was told to follow a offset limit format, but unsure how to set the offsets. Should I add extra parameters here as offsets and from client call this api in a loop? Or if there is a better way to do this please help

CodePudding user response:

HTTP request has a single response. If you want to break the results into batches then you can make front end sending offset and the size and get batches of results. Refer the concept of pagination. The best practice should be using:

Pageable pageable = PageRequest.of(0, 20);

Pass the params for this from the front end and call repeatedly

CodePudding user response:

This is possible if you return ResponseEntity of Resource type:

@GetMapping(value = "/employees")
    public ResponseEntity<Resource> findAllEmployees() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        byte[] array = mapper.writeValueAsBytes(employeeService.getAllEmployees());
        Resource resource = new ByteArrayResource(array);
        return ResponseEntity.status(HttpStatus.OK).body(resource);
    }
  • Related