Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In this article, you extend the application you created in Build TypeScript apps with Microsoft Graph and app-only authentication with Microsoft Graph user APIs. You use Microsoft Graph to list users in your organization.
Open graphHelper.ts and add the following function.
export async function getUsersAsync(): Promise<PageCollection> { // Ensure client isn't undefined if (!_appClient) { throw new Error('Graph has not been initialized for app-only auth'); } return _appClient ?.api('/users') .select(['displayName', 'id', 'mail']) .top(25) .orderby('displayName') .get(); }
Replace the empty
listUsersAsync
function in index.ts with the following.async function listUsersAsync() { try { const userPage = await graphHelper.getUsersAsync(); const users: User[] = userPage.value; // Output each user's details for (const user of users) { console.log(`User: ${user.displayName ?? 'NO NAME'}`); console.log(` ID: ${user.id}`); console.log(` Email: ${user.mail ?? 'NO EMAIL'}`); } // If @odata.nextLink is not undefined, there are more users // available on the server const moreAvailable = userPage['@odata.nextLink'] != undefined; console.log(`\nMore users available? ${moreAvailable}`); } catch (err) { console.log(`Error getting users: ${err}`); } }
Run the app, sign in, and choose option 2 to list users.
[1] Display access token [2] List users [3] Make a Graph call [0] Exit Select an option [1...3 / 0]: 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? true
Code explained
Consider the code in the getUsersAsync
function.
- It gets a collection of users
- It uses
select
to request specific properties - It uses
top
to limit the number of users returned - It uses
orderBy
to sort the response