Skip to content

Commit

Permalink
Merge pull request #358 from earthquakesan/main
Browse files Browse the repository at this point in the history
Add example of searching user by name
  • Loading branch information
samwelkanda authored Sep 25, 2023
2 parents b8c1cb8 + 668ef4c commit a9ac3b8
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion docs/users_samples.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,50 @@ async def get_memberships():
group = await client.groups.by_group_id(obj.id).get()
if group:
print(group.id, group.group_types, group.display_name, group.mail)
asyncio.run(get_memberships())
asyncio.run(get_memberships())
```

## 3. SEARCH USER BY NAME (GET /users/$search?=)

```py
import asyncio

from azure.identity import AzureCliCredential
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder


async def find_user(user_name: str, client: GraphServiceClient) -> None:
# The query used here is the same when searching for users in Azure AD via web console
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
search=[
f'("displayName:{user_name}" OR "mail:{user_name}" OR "userPrincipalName:{user_name}" OR "givenName:{user_name}" OR "surName:{user_name}" OR "otherMails:{user_name}")'
],
)
request_configuration = (
UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(
query_parameters=query_params, headers={"ConsistencyLevel": "eventual"}
)
)

response = await client.users.get(request_configuration=request_configuration)
if response.value:
user = response.value[0]
print(
f"Found user for {user_name} in the Azure AD with user principal name {user.user_principal_name} and display name {user.display_name}"
)
else:
print(f"{user_name} user in the Azure AD not found")


def main():
# Use cli credentials to authenticate against Azure
# Before running script do `az login`
credential = AzureCliCredential()
scopes = ["https://graph.microsoft.com/.default"]
client = GraphServiceClient(credentials=credential, scopes=scopes)
asyncio.run(find_user("john", client))


main()
```

0 comments on commit a9ac3b8

Please sign in to comment.