Vasanth Subramanian
Vasanth Subramanian

Reputation: 1341

REST API to send processing status

Working on implementing a REST API using Spring Boot. Consumer is an Angular based application.

REST API takes two CSV files as input. It does processing in several stages. I want to update the stage-wise completion status as intermediate response. Is it possible to achieve this? Please advise.

@PostMapping("/process/")
public ResponseEntity process(@RequestParam("csv1") MultipartFile csv1,
                          @RequestParam("csv2") MultipartFile csv2) {

    Generator generator = new Generator();

    try {
        generator.parseCSV1File(csv1.getInputStream());
        //TO SEND PARSING OF CSV 1 is COMPLETE

        generator.parseCSV2File(csv2.getInputStream());
        //TO SEND PARSING OF CSV 2 is COMPLETE

        List<String> viewScripts = generator.generateViewScript();
        //TO SEND VIEW SCRIPT is GENERATED
    
        return ResponseEntity.ok().body(viewScripts);

    } catch (Exception ex) {
        logger.severe("Error in processing: " + ex);
        return ResponseEntity.ok(HttpStatus.EXPECTATION_FAILED);
    }
}

Upvotes: 1

Views: 1229

Answers (1)

ttarczynski
ttarczynski

Reputation: 1014

With a HTTP-only based solution, sending an "intermediate" response is not possible. HTTP is a request-response based protocol, and for a single request you get a single response. Since you're triggering a long running process, you have to wait until the process is complete to get the response.

But there'are solutions! A simple one is to use polling:

  1. On the /process/ request; 1.1 Create an id of the process 1.2 Start the process in a separate thread, not to block the caller until the process is complete 1.3 Return the identifier to the client application
  2. In the background process update its status saving it, say, in the database or a simple flat file (whatever works for you ;-))
  3. Create another endpoint, which will be used by the frontend application to periodically check (poll) what is the current status of the process. The path can be /process/{process-id}/status
  4. In the frontend application periodically check the status using the newly created endpoint

There are other solutions of course, but polling may be the most simple, and easy to implement, and will keep you in the HTTP, "RESTish" world ;-)

Upvotes: 2

Related Questions