Some Google Cloud APIs return lists of resources that are too
large to fit in a single response. These APIs implement pagination as described
in the AIP-158 pagination specification on
google.aip.dev. The service returns a single page of results along with a
nextPageToken value that the client can include in subsequent requests to
fetch the next page.
The Google Cloud client libraries for Swift support paginated RPCs by
providing AsyncSequence helpers that handle page tokens and fetch subsequent
pages as you iterate over the results. This document shows you how to use both
automatic iteration and manual page-by-page fetching.
Before you begin
This document uses the Secret Manager API. To enable this API, follow
the Secret Manager quickstart. Verify that your
principal has permissions to list secrets, such as the Secret Manager Viewer
Identity and Access Management (IAM) role (roles/secretmanager.viewer).
For complete setup instructions for the Swift client libraries, see Quickstart: Get started with Swift.
Iterate over items automatically
To handle paginated results in Swift, iterate over the items using a for try
await loop. The client library fetches subsequent pages on demand as you
iterate. To iterate over items automatically, follow these steps:
Add the imports required to use the client library:
Define a function that accepts the project ID as a parameter:
Initialize the client with the default options:
Construct a
ListSecretsRequest(optionally settingpageSize), request an asynchronous sequence of items using theMETHODByItemshelper method (in this example,listSecretsByItems(request:)), and iterate over the results:
Iterate page by page manually
If your app needs direct access to individual pages and page tokens, call the standard request method to receive the raw page response. This approach is useful when implementing your own pagination layer in a web service. To manage page tokens yourself, follow these steps:
Create a function that initializes the client:
Make paginated requests using the
listSecrets(request:)method, inspect the items on each page, and use the returnednextPageTokenvalue to fetch subsequent pages:
When you run either function against a project with secrets, it prints each secret resource name to standard output.
Complete code
The following example shows the complete code for this document:
What's next
- Learn how to call long-running operations.
- Learn how to update a resource using a field mask.
- Learn how to override the default retry policies.
- Learn how to enable debug logging to troubleshoot requests and responses.
- Browse the Google Cloud client libraries for Swift reference documentation.