简体   繁体   中英

RESTful API with Batch Requests

We have a not so RESTful API used by our single page app and mobile apps.

It is not so RESTfu since in the past, URI's have returned whatever was useful for a particular page. This has led to a large number of endpoints, with many having very similar responses.

Datawise we have resources with tens of related resources. In some cases we want those related resources returned, or some of them, and other cases we do not. Some are slow to return, and therefore we only want them in specific cases.

The problem we've had has been with splitting the data up into meaningful URI's, without needing another request to get each related resource.

we therefore considered a /batch endpoint where a POST request containing a number of requests in the body could execute those requests in parallel on the server. Like this https://developers.facebook.com/docs/graph-api/making-multiple-requests

That way we could split the data into meaningful URI's and not have to make 20 API requests for each page.

Is this an acceptable way of handling related resources? Or would it be better to have a URI for each response that we may want?

HTTP/2 will make this problem go away by allowing you to multiplex requests on a single connection.

In the meanwhile, I would suggest that you are not violating any REST constraints with your current solution. However, creating a batch of requests breaks the resource identification constraint which will have a major impact on the cacheability of representations.

Batching is fine -- don't let RESTful design patterns steer you down a path to bad performance.

It is likely that your batching solution can be designed such that each piece that can be batched can be called separately. If so, it might be straightforward to create RESTful endpoints for each as well, for those who would want that at the expense of multiple round-trips.

You can also use query parameters to select different, packaged returns of resources. For example, for a user, you could use something like:

GET /v1/users/1?related={none,all,basic}

You could also use a field selector:

GET /v1/users/1?data=addresses,history

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM