UserCollectionPage has an API "getCurrentPage()" type List<User> which returns only 100 users from directory

Viewed 551

I am trying to access a b2c directory using Graph API to get all the users inside it...So far I have 800+ users however using below snippet I could only get 100 users.

UserCollectionPage users = graphClient.users()
                .buildRequest()
                .get();

List<User> userList = users.getCurrentPage();

So I have created a graph client and ideally I should get back all the users in object "users" however I was only able to get 100 users, I tried to debug and found so...

One more bug that I noticed in the API was that the userType in debugger expression window for all user was NULL which is wrong because all the users are of userType - member...

Is anybody aware of what the correct API is to list all the users at once? I do not mind if the listing is based on JSON, but the more important thing would be to list all 800+ users.

2 Answers

So here is the trick...

In Azure b2c AD, users are stored "page" wise, one single page can store a maximum of 100 users and one API call - can present you a top/max of 999 users...but what if you have more than 999 users?

So here is how you can paginate users and get them in a List.

        List<List<User>> allUserList = new ArrayList<>();
        
        UserCollectionPage users = graphClient.users()
                .buildRequest()
                .get();
        
        do {
            List<User> currentPageUser = users.getCurrentPage();
                        Collections.addAll(allUserList, currentPageUser);
                        UserCollectionRequestBuilder nextPage = users.getNextPage();
            users = nextPage == null ? null : nextPage.buildRequest().get();
        } while (users != null);
        
        return allUserList;

So once you have List of pages as List and each page will have 100 users...

So if you have 876 users, you will have 8 pages with first 7 pages with 100 users and 8th page with 76 users...

Related