Batch Resources Endpoint in REST API Design

Sometimes in a REST API we want a single endpoint to be able to return multiple types of resources at once.

Some names for this are a batch resources endpoint or simply batch endpoint; another name is bulk endpoint.

The endpoint itself could use the resource name “/batch-resources” or simply “/batch”.

Suppose we have a public library system API. The batch call could look like the following:

GET /batch-resources?list=(/locations,/books,/authors)

The returned result can be organized by resource:

{
  "locations": [
    {
      "id" 1,
      ...
    },
    ...
  ],
  "books": [
    {
      "id": 1,
      ...
    },
    ...
  ],
  "authors": [
    {
      "id": 1,
      ...
    },
    ...
  ]
}

If we need filters or sub-resources we can pass them with the individual resources listed, as if they were individual calls. For example:

GET /batch-resources?list=(/authors?q=term,/authors/1/books)

In this case the results should contain the full request paths and query strings as the keys:

{
  "authors?q=terms": [ ... ],
  "authors/1/books": [ ... ]
}

Although GET feels most natural and is the proper REST verb here, if we need very complex requests all at once in the batch request, we could use a POST request with the specific requests in the POST body. For example:

POST /batch-resources
{
  "requests": [
    "/locations?q=term",
    "/books?q=term",
    "/authors?q=term"
  ]
}

The returned response would again be organized by request key.

Using POST would have the advantage of a much larger potential body for the query; a very large GET request may not be enough when reaching the length limit of the query string.

Note that if you need a very flexible API with batch requests, especially serving many different clients with different requirements, it may be appropriate to consider GraphQL.