API Design: Paginated Responses by Default

One important way to reduce performance issues and potential abuse in an API is using pagination by default.

For example, suppose we have a call like:

GET /items

Conceptually, this REST resource represents a list of all items available.

In a real production API, however, this should default to actually getting the first page only. Specifically:

GET /items

should be an equivalent call to:

GET /items?page=1

This is because as the items collection grows, in theory the list of all items can become extremely large.

If /items attempts to return all items at once, the endpoint becomes a performance problem and a potential API security issue: it opens the API up to Resource Exhaustion Attacks. Attackers can abuse the API by requesting very large lists repeatedly, in parallel, potentially depleting server resources and causing denial-of-service to legitimate users.
Implemeting pagination-by-default helps prevent this abuse.

There should also be a hard limit on the maximum page size, for calls where the page size is specified.
For example, 500 items could be a hard maximum.
For any larger page sizes, we can return an error such as the following:

GET /items?pageSize=501
400 Bad request
{
  "error": Page size too large"
}

Following these guidelines will help an API be more performant and resistant to abuse.

 

Leave a Reply

Your email address will not be published. Required fields are marked *