arslan
arslan

Reputation: 2224

Rest API, where to put heavy computation in routes?

I am intending to design a Rest API, which receives user request and do heavy computation and return the result.

I am new to web programming. so just get familiar with basic API service.

what I know:

1) request sent by post method with JSON, because data is not so simple. 2) I followed some examples and been successful with basics.

so I think I better start writing the heavy computation part.

I want it as following.

1) receive post request, and start to compute

2) just after computing send "working msg" (I think I can just do re.send("MSG"))

my questions

1)but where should I put my heavy computing?

2)since I already responded with "MSG", how can I send another content when there is no request?

3) I have read about middleware, and feels like middleware handles things between receiving request and sending response. am I right?

It would be great if you could show me a simple examples.

Upvotes: 2

Views: 1703

Answers (1)

laurent
laurent

Reputation: 90746

Probably the best way to implement this is to do the heavy processing server-side in the background, and provide a way for the client to check if the job is completed or not.

For example, let's say you want to run some heavy calculation. You could create a resource like this:

POST /calculator

The client POST a calculation, then the resource queue the calculation job for later processing (maybe by some cron job on the server) and respond with a job resource:

{ "id": 123456, "status": "pending" }

Then the clients can check at any time if the job is completed by checking the /jobs resource:

GET /jobs/123456

which initially might respond with this again:

{ "id": 123456, "status": "pending" }

Then when it's in progress:

{ "id": 123456, "status": "in_progress" }

And when it's done:

{ "id": 123456, "status": "done", "result": <some object that contains the result of the calculation> }

Upvotes: 9

Related Questions