Pagination

Pagination screencast
Watch the Pagination screencast

API Platform has native support for paged collections. Pagination is enabled by default for all collections. Each collection contains 30 items per page.

The activation of the pagination and the number of elements per page can be configured from:

  • the server-side (globally or per resource)
  • the client-side, via a custom GET parameter (disabled by default)

When issuing a GET request on a collection containing more than 1 page (here /books), a Hydra collection is returned. It's a valid JSON(-LD) document containing items of the requested page and metadata.

{
  "@context": "/contexts/Book",
  "@id": "/books",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/books/1",
      "@type": "https://schema.org/Book",
      "name": "My awesome book"
    },
    {
      "_": "Other items in the collection..."
    }
  ],
  "hydra:totalItems": 50,
  "hydra:view": {
    "@id": "/books?page=1",
    "@type": "hydra:PartialCollectionView",
    "hydra:first": "/books?page=1",
    "hydra:last": "/books?page=2",
    "hydra:next": "/books?page=2"
  }
}
{
  "@context": "/contexts/Book",
  "@id": "/books",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/books/1",
      "@type": "https://schema.org/Book",
      "name": "My awesome book"
    },
    {
      "_": "Other items in the collection..."
    }
  ],
  "hydra:totalItems": 50,
  "hydra:view": {
    "@id": "/books?page=1",
    "@type": "hydra:PartialCollectionView",
    "hydra:first": "/books?page=1",
    "hydra:last": "/books?page=2",
    "hydra:next": "/books?page=2"
  }
}

Hypermedia links to the first, the last, previous and the next page in the collection are displayed as well as the number of total items in the collection.

The name of the page parameter can be changed with the following configuration:

# api/config/packages/api_platform.yaml
api_platform:
  collection:
    pagination:
      page_parameter_name: page # Default value
# api/config/packages/api_platform.yaml
api_platform:
  collection:
    pagination:
      page_parameter_name: page # Default value

If you are using custom state providers (not the provided Doctrine ORM, ODM or ElasticSearch ones) and if you want your results to be paginated, you will need to return an instance of a ApiPlatform\State\Pagination\PartialPaginatorInterface or ApiPlatform\State\Pagination\PaginatorInterface.

A few existing classes are provided to make it easier to paginate the results:

  • ApiPlatform\State\Pagination\ArrayPaginator
  • ApiPlatform\State\Pagination\TraversablePaginator

For more examples, read our guide on how to handle a pagination on a custom collection.

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop