Page through a collection using the Microsoft Graph SDKs
Article
For performance reasons, collections of entities are often split into pages and each page is returned with a URL to the next page. The PageIterator class simplifies consuming of paged collections. PageIterator handles enumerating the current page and requesting subsequent pages automatically.
Request headers
If you send any additional request headers in your initial request, those headers are not included by default in subsequent page requests. If those headers need to be sent on subsequent requests, you must set them explicitly.
Iterate over all the messages
The following example shows iterating over all the messages in a user's mailbox.
Tip
This example sets a small page size using the top parameter for demonstration purposes. You can set the page size up to 999 to minimize the number of requests that are necessary.
headers := abstractions.NewRequestHeaders()
headers.Add("Prefer", "outlook.body-content-type=\"text\"")
var pageSize int32 = 10
query := users.ItemMessagesRequestBuilderGetQueryParameters{
Select: []string{"body", "sender", "subject"},
Top: &pageSize,
}
options := users.ItemMessagesRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: &query,
}
result, err := graphClient.Me().Messages().Get(context.Background(), &options)
if err != nil {
log.Fatalf("Error getting messages: %v\n", err)
}
// Initialize iterator
pageIterator, err := graphcore.NewPageIterator[*models.Message](
result,
graphClient.GetAdapter(),
models.CreateMessageCollectionResponseFromDiscriminatorValue)
if err != nil {
log.Fatalf("Error creating page iterator: %v\n", err)
}
// Any custom headers sent in original request should also be added
// to the iterator
pageIterator.SetHeaders(headers)
// Iterate over all pages
err = pageIterator.Iterate(
context.Background(),
func(message *models.Message) bool {
fmt.Printf("%s\n", *message.GetSubject())
// Return true to continue the iteration
return true
})
if err != nil {
log.Fatalf("Error iterating over messages: %v\n", err)
}
Note
The Microsoft Graph Java SDK does not currently have a PageIterator class. Instead, you need to request each page as shown in the following code.
MessageCollectionPage messagesPage = graphClient.me().messages()
.buildRequest(
new HeaderOption("Prefer", "outlook.body-content-type=\"text\""))
.select("sender,subject,body").top(10).get();
while (messagesPage != null) {
final List<Message> messages = messagesPage.getCurrentPage();
for (Message message : messages) {
System.out.println(message.subject);
}
// Get the next page
final MessageCollectionRequestBuilder nextPage = messagesPage.getNextPage();
if (nextPage == null) {
break;
} else {
messagesPage = nextPage.buildRequest(
// Re-add the header to subsequent requests
new HeaderOption("Prefer", "outlook.body-content-type=\"text\""))
.get();
}
}
const response: PageCollection = await graphClient
.api('/me/messages?$top=10&$select=sender,subject,body')
.header('Prefer', 'outlook.body-content-type="text"')
.get();
// A callback function to be called for every item in the collection.
// This call back should return boolean indicating whether not to
// continue the iteration process.
const callback: PageIteratorCallback = (message: Message) => {
console.log(message.subject);
return true;
};
// A set of request options to be applied to
// all subsequent page requests
const requestOptions: GraphRequestOptions = {
// Re-add the header to subsequent requests
headers: {
Prefer: 'outlook.body-content-type="text"',
},
};
// Creating a new page iterator instance with client a graph client
// instance, page collection response from request and callback
const pageIterator = new PageIterator(
graphClient,
response,
callback,
requestOptions
);
// This iterates the collection until the nextLink is drained out.
await pageIterator.iterate();
Stopping and resuming the iteration
Some scenarios require stopping the iteration process in order to perform other actions. It is possible to pause the iteration by returning false from the iteration callback. Iteration can be resumed by calling the resume method on the PageIterator.