Spotify.NET/SpotifyAPI.Docs/docs/pagination.md
Nova 300c51db3c
Minor fixes for comprehesion (#507)
Fixed capitalization, spelling, grammar, added gender-neutral language
2020-09-16 09:13:21 +02:00

2.9 KiB

id title
pagination Pagination

When working with Spotify responses, you will often encounter the Paging<T> type.

The offset-based paging object is a container for a set of objects. It contains a key called Items (whose value is an array of the requested objects) along with other keys like Previous, Next and Limit which can be useful in future calls.

It allows you to only receive a subset of all available data and dynamically check if more requests are required. The library supports Paging<T> responses in two ways:

PaginateAll

PaginateAll will query all remaining elements based on a first page and return all of them in an IList. This method should not be used for huge amounts of pages (e.g Search Endpoint), since it stores every response in memory.

// we need the first page
var page = await spotify.Playlists.CurrentUsers();

// allPages will include the first page retrived before
var allPages = await spotify.PaginateAll(page);

Paginate

:::info .NET Standard >= 2.1 required :::

Paginate is based on IAsyncEnumerable and streams pages instead of returning them all in one list. This allows it to break the fetching early and keep only 1 page in memory at a time. This method should always be preferred to PaginateAll.

// we need the first page
var page = await spotify.Playlists.CurrentUsers();

await foreach(var item in spotify.Paginate(page))
{
  Console.WriteLine(item.Name);
  // you can use "break" here!
}

Some endpoints have nested and/or multiple paginations objects. When requesting the next page, it will not return the actual paging object but rather the root level endpoint object. A good example is the Search endpoint, which contains up to 5 Paging objects. Requesting the next page of the nested Artists paging object will return another Search response, instead of just Artists. You will need to supply a mapper function to the Paginate call, which returns the correct paging object:

var search = await spotify.Search.Item(new SearchRequest(
  SearchRequest.Types.All, "Jake"
));

await foreach(var item in spotify.Paginate(search.Albums, (s) => s.Albums))
{
  Console.WriteLine(item.Name);
  // you can use "break" here!
}

Paginators

Via the interface IPaginator, it can be configured how pages are fetched. It can be configured on a global level:

var config = SpotifyClientConfig
  .CreateDefault()
  .WithPaginator(new YourCustomPaginator());

or on method level:

await foreach(var item in spotify.Paginate(page, new YourCustomPaginator()))
{
  Console.WriteLine(item.Name);
  // you can use "break" here!
}

By default, SimplePaginator is used. It fetches pages without any delay.