Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST service for stateless computation

I need to create a method in my REST API that will be used to perform some computation. For sake of simplicity, assume that I need to implement a method that for a given list of objects will return its length.

It should only compute the length and return to the client, so no resource will be modified server side. As it does not modify any resources, one would expect that it should be a GET request. However, as the list may be large and the objects may be complex, it looks like I need to make it as a POST request. This would however violate the standard that POST is used in REST to create resources.

What would be your solution to this problem?

like image 907
jfu Avatar asked Feb 11 '23 13:02

jfu


1 Answers

First solution

According to RESTful Web Services Cookbook you can treat your computation as a resource and just GET it. For example:

-- Request
GET /computations?param1=2&param2=2 HTTP/1.1

-- Response
HTTP/1.1 200 OK
Content-Type: application/json

{
    "result": 4
}

It sounds good for fast computations with small amount of input parameters. But if your computation isn't that then you can use second solution.

Second solution

Treat both computation and result as resources. POST computation and GET result. For example:

First you create a computation

-- Request
POST /computations HTTP/1.1
Content-Type: application/json

{
    "param1": 2,
    "param2": 2
}

-- Response
HTTP/1.1 201 Created
Location: /computations/1

Then you can get this computation

-- Request
GET /computations/1 HTTP/1.1

-- Response
HTTP/1.1 200 OK
Content-Type: application/json

{
    "param1": 2,
    "param2": 2
}

But also you can get a result (/computations/1/result) of this computation

-- Request
GET /computations/1/result HTTP/1.1

-- Response
HTTP/1.1 204 No Content
Cache-Control: max-age=3600,must-revalidate

But oh no! There is no result yet. Server tells us to come back in an hour (Cache-Control: max-age=3600,must-revalidate) and try again. The second solution allows you to make computation asynchronous (in case when it takes a lot of time) or you can compute it once, store the result in some DB and serve it quickly when requested for the next time.

-- Request
GET /computations/1/result HTTP/1.1

-- Response
HTTP/1.1 200 OK
Content-Type: application/json

{
    "result": 4
}
like image 81
emstol Avatar answered Feb 13 '23 03:02

emstol