|
| 1 | +## Create the API Client |
| 2 | + |
| 3 | +```py |
| 4 | +import asyncio |
| 5 | + |
| 6 | +from azure.identity import ClientSecretCredential |
| 7 | +from kiota_abstractions.api_error import APIError |
| 8 | +from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider |
| 9 | +from msgraph import GraphRequestAdapter, GraphServiceClient |
| 10 | + |
| 11 | +# Set the event loop policy for Windows |
| 12 | +asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) |
| 13 | + |
| 14 | +# Create authentication provider object. Used to authenticate request |
| 15 | +credential = ClientSecretCredential( |
| 16 | + tenant_id='TENANT_ID', |
| 17 | + client_id='CLIENT_ID', |
| 18 | + client_secret='CLIENT_SECRET' |
| 19 | +) |
| 20 | +scopes = ['https://graph.microsoft.com/.default'] |
| 21 | +auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes) |
| 22 | + |
| 23 | +# Initialize a request adapter with the auth provider. |
| 24 | +request_adapter = GraphRequestAdapter(auth_provider) |
| 25 | + |
| 26 | +# Create an API client with the request adapter. |
| 27 | +client = GraphServiceClient(request_adapter) |
| 28 | +``` |
| 29 | + |
| 30 | +## 1. GET ALL USERS IN A TENANT (GET /users) |
| 31 | + |
| 32 | +```py |
| 33 | +async def get_users(): |
| 34 | + try: |
| 35 | + users = await client.users.get() |
| 36 | + if users and users.value: |
| 37 | + for user in users.value: |
| 38 | + print(user.id, user.display_name, user.mail) |
| 39 | + except APIError as e: |
| 40 | + print(e.error.message) |
| 41 | +asyncio.run(get_users()) |
| 42 | +``` |
| 43 | + |
| 44 | +## 2. GET A SPECIFIC USER (GET /users/{id | userPrincipalName}) |
| 45 | + |
| 46 | +```py |
| 47 | +async def get_user(): |
| 48 | + try: |
| 49 | + user = await client.users_by_id('USER_ID').get() |
| 50 | + if user: |
| 51 | + print(user.user_principal_name, user.display_name, user.id) |
| 52 | + except APIError as e: |
| 53 | + print(f'Error: {e.error.message}') |
| 54 | +asyncio.run(get_user()) |
| 55 | + |
| 56 | +# LIST ALL TRANSITIVE MEMBERSHIPS OF A USER (GET /users/{id}/transitiveMemberOf) |
| 57 | + |
| 58 | +async def get_memberships(): |
| 59 | + try: |
| 60 | + memberships = await client.users_by_id('USER_ID').transitive_member_of.get() |
| 61 | + if memberships and memberships.value: |
| 62 | + for membership in memberships.value: |
| 63 | + obj = await client.directory_objects_by_id(membership.id).get() |
| 64 | + if obj and obj.odata_type == '#microsoft.graph.group': |
| 65 | + group = await client.groups_by_id(obj.id).get() |
| 66 | + if group: |
| 67 | + print(group.id, group.group_types, group.display_name, group.mail) |
| 68 | + except Exception as e: |
| 69 | + print(e) |
| 70 | +asyncio.run(get_memberships()) |
0 commit comments