Skip to content

Commit 8a55eb0

Browse files
committed
Add example of searching user by name
Provide an end2end example on how to initialize users request with query parameters and search query. Reproduce the same behaviour as in the Azure AD web console search.
1 parent 20eda09 commit 8a55eb0

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

docs/users_samples.md

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,50 @@ async def get_memberships():
4949
group = await client.groups.by_group_id(obj.id).get()
5050
if group:
5151
print(group.id, group.group_types, group.display_name, group.mail)
52-
asyncio.run(get_memberships())
52+
asyncio.run(get_memberships())
53+
```
54+
55+
## 3. SEARCH USER BY NAME (GET /users/$search?=)
56+
57+
```py
58+
import asyncio
59+
60+
from azure.identity import AzureCliCredential
61+
from msgraph import GraphServiceClient
62+
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
63+
64+
65+
async def find_user(user_name: str, client: GraphServiceClient) -> None:
66+
# The query used here is the same when searching for users in Azure AD via web console
67+
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
68+
search=[
69+
f'("displayName:{user_name}" OR "mail:{user_name}" OR "userPrincipalName:{user_name}" OR "givenName:{user_name}" OR "surName:{user_name}" OR "otherMails:{user_name}")'
70+
],
71+
)
72+
request_configuration = (
73+
UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
74+
query_parameters=query_params, headers={"ConsistencyLevel": "eventual"}
75+
)
76+
)
77+
78+
response = await client.users.get(request_configuration=request_configuration)
79+
if response.value:
80+
user = response.value[0]
81+
print(
82+
f"Found user for {user_name} in the Azure AD with user principal name {user.user_principal_name} and display name {user.display_name}"
83+
)
84+
else:
85+
print(f"{user_name} user in the Azure AD not found")
86+
87+
88+
def main():
89+
# Use cli credentials to authenticate against Azure
90+
# Before running script do `az login`
91+
credential = AzureCliCredential()
92+
scopes = ["https://graph.microsoft.com/.default"]
93+
client = GraphServiceClient(credentials=credential, scopes=scopes)
94+
asyncio.run(find_user("john", client))
95+
96+
97+
main()
98+
```

0 commit comments

Comments
 (0)