Пространство имен: microsoft.graph
Важно!
API версии /beta в Microsoft Graph могут быть изменены. Использование этих API в производственных приложениях не поддерживается. Чтобы определить, доступен ли API в версии 1.0, используйте селектор версий.
Получение списка объектов user. Этот API также возвращает объекты agentUser .
Эта операция по умолчанию возвращает только подмножество наиболее часто используемых свойств для каждого пользователя и agentUser. Эти свойства по умолчанию указаны в разделе Свойства. Чтобы получить свойства, которые не возвращаются по умолчанию, выполните операцию GET и укажите их в параметре запроса OData $select.
Этот API доступен в следующих национальных облачных развертываниях.
| Глобальная служба |
Правительство США L4 |
Правительство США L5 (DOD) |
Китай управляется 21Vianet |
| ✅ |
✅ |
✅ |
✅ |
Разрешения
Выберите разрешение или разрешения, помеченные как наименее привилегированные для этого API. Используйте более привилегированное разрешение или разрешения только в том случае, если это требуется приложению. Дополнительные сведения о делегированных разрешениях и разрешениях приложений см. в разделе Типы разрешений. Дополнительные сведения об этих разрешениях см. в справочнике по разрешениям.
| Тип разрешения |
Разрешение с наименьшими привилегиями |
Более высокие привилегированные разрешения |
| Делегированные (рабочая или учебная учетная запись) |
User.ReadBasic.All |
User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All |
| Делегированные (личная учетная запись Майкрософт) |
Не поддерживается. |
Не поддерживается. |
| Для приложений |
User.Read.All |
User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All |
Разрешения для определенных сценариев
-
User-Mail.ReadWrite.All — это наименее привилегированное разрешение на чтение и запись свойства otherMails ; также позволяет считывать некоторые свойства, связанные с идентификатором, в объекте пользователя.
-
User-PasswordProfile.ReadWrite.All — это наименее привилегированное разрешение на чтение и запись свойств, связанных со сбросом пароля; также позволяет считывать некоторые свойства, связанные с идентификатором, в объекте пользователя.
-
User-Phone.ReadWrite.All — это наименее привилегированное разрешение на чтение и запись свойств businessPhones и mobilePhone ; также позволяет считывать некоторые свойства, связанные с идентификатором, в объекте пользователя.
-
User.EnableDisableAccount.All + User.Read.All — это наименее привилегированное сочетание разрешений на чтение и запись свойства accountEnabled .
HTTP-запрос
Следующий URL-адрес возвращает список объектов user и agentUser с объектами agentUser, содержащими свойство @odata.type .#microsoft.graph.agentUser
GET /users
Необязательные параметры запросов
Этот метод поддерживает параметры запроса OData для настройки ответа:
-
$count, $expand, $filter, $orderby, $search, $select, $top. Параметр $skip не поддерживается.
- Чтобы отфильтровать пользователей агента из результирующих наборов, используйте
isof функцию : $filter=isof('microsoft.graph.agentUser') возвращает только пользователей агента, а $filter=not isof('microsoft.graph.agentUser') исключает пользователей агента.
-
Ограничения на размер страницы: Размер страницы по умолчанию — 100 объектов. Максимальный размер страницы — 999 объектов, за исключением случаев использования
$select=signInActivity или $filter=signInActivity, максимальный размер страницы — 500.
- Для некоторых запросов необходимо задать для заголовка ConsistencyLevel значение
eventual и $count. Дополнительные сведения см. в разделе Расширенные возможности запросов к объектам каталогов.
- Параметры
$count и $search недоступны в Azure AD клиентах B2C.
Свойства расширения также поддерживают параметры запроса следующим образом:
| Тип расширения |
Комментарии |
| onPremisesExtensionAttributes 1-15 |
Возвращается только с помощью $select. Поддерживает $filter (eq, ne и eq по null значениям). |
| Расширения схемы |
Возвращается только с помощью $select. Поддерживает $filter (eq, ne и eq по null значениям). |
| Открытые расширения |
Возвращается только с $expand, то есть users?$expand=extensions. |
| Расширения каталога |
Возвращается только с помощью $select. Поддерживает $filter (eq, ne и eq по null значениям). |
Для объектов agentUser неприменимые свойства всегда nullимеют значение .
Определенные свойства не могут быть возвращены в коллекции пользователей. Следующие свойства поддерживаются только при получении одного пользователя: aboutMe, birthday, hireDate, interests, mySite, pastProjects, preferredName, обязанности, учебные заведения, навыки, mailboxSettings.
Следующие свойства не поддерживаются в личных учетных записях Майкрософт и всегда null: aboutMe, день рождения, интересы, mySite, pastProjects, preferredName, обязанности, учебные заведения, навыки, streetAddress.
Текст запроса
Не указывайте текст запроса для этого метода.
Отклик
В случае успешного 200 OK выполнения этот метод возвращает код отклика и коллекцию объектов user и agentUser в теле отклика. Объекты agentUser включают свойство @odata.type со значением#microsoft.graph.agentUser, которое отличает их от пользовательских объектов.
Попытка использовать $select в /users коллекции для получения свойств, которые не могут быть возвращены в коллекции (например, запрос ../users?$select=aboutMe), возвращает 501 Not Implemented код ошибки.
Примеры
Пример 1. Получение всех пользователей
Запрос
Ниже показан пример запроса. Ответ включает пользователей агента.
GET https://graph.microsoft.com/beta/users
GET https://graph.microsoft.com/beta/users
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync();
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
//other-imports
)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get();
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$result = $graphServiceClient->users()->get()->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
result = await graph_client.users.get()
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"value":[
{
"displayName":"contoso1",
"mail":"'contoso1@gmail.com",
"mailNickname":"contoso1_gmail.com#EXT#",
"otherMails":["contoso1@gmail.com"],
"proxyAddresses":["SMTP:contoso1@gmail.com"],
"userPrincipalName":"contoso1_gmail.com#EXT#@contoso.com"
}
]
}
Пример 2. Получение только пользователей агента
Запрос
Ниже показан пример запроса.
GET https://graph.microsoft.com/beta/users/microsoft.graph.agentUser
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users["{user-id}"].GetAsync();
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
//other-imports
)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().ByUserId("user-id").Get(context.Background(), nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
User result = graphClient.users().byUserId("{user-id}").get();
const options = {
authProvider,
};
const client = Client.init(options);
let agentUser = await client.api('/users/microsoft.graph.agentUser')
.version('beta')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$result = $graphServiceClient->users()->byUserId('user-id')->get()->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -UserId $userId
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
result = await graph_client.users.by_user_id('user-id').get()
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"value":[
{
"@odata.type":"#microsoft.graph.agentUser",
"displayName":"contoso1",
"mail":"'contoso1@gmail.com",
"mailNickname":"contoso1_gmail.com#EXT#",
"otherMails":["contoso1@gmail.com"],
"proxyAddresses":["SMTP:contoso1@gmail.com"],
"userPrincipalName":"contoso1_gmail.com#EXT#@contoso.com"
}
]
}
Пример 3. Получение учетной записи пользователя с помощью имени входа
Найдите учетную запись пользователя, используя имя для входа (также называемое локальной учетной записью).
Примечание. При фильтрации по свойству issuerAssignedId требуется указывать параметры issuer и issuerAssignedId. Однако в некоторых сценариях значение issuer будет игнорироваться. Дополнительные сведения о фильтрации удостоверений см. в типе ресурса objectIdentity.
Запрос
Ниже показан пример запроса.
GET https://graph.microsoft.com/beta/users?$select=displayName,id&$filter=identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string []{ "displayName","id" };
requestConfiguration.QueryParameters.Filter = "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')";
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestFilter := "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Select: [] string {"displayName","id"},
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.select = new String []{"displayName", "id"};
requestConfiguration.queryParameters.filter = "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')";
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.filter('identities/any(c:c/issuerAssignedId eq \'j.smith@yahoo.com\' and c/issuer eq \'My B2C tenant\')')
.select('displayName,id')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->select = ["displayName","id"];
$queryParameters->filter = "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')";
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Property "displayName,id" -Filter "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select = ["displayName","id"],
filter = "identities/any(c:c/issuerAssignedId eq 'j.smith@yahoo.com' and c/issuer eq 'My B2C tenant')",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"value": [
{
"displayName": "John Smith",
"id": "87d349ed-44d7-43e1-9a83-5f2406dee5bd"
}
]
}
Пример 4. Получение гостевых пользователей (B2B) из определенного клиента или домена по userPrincipalName
Запрос
Ниже показан пример запроса. Значение userPrincipalName для гостевых пользователей (совместная работа B2B) всегда содержит идентификатор "#EXT#". Например, userPrincipalName пользователя в домашнем клиенте имеет значение AdeleV@adatum.com. При приглашении пользователя для совместной работы в клиенте contoso.com его userPrincipalName в клиенте будет "AdeleV_adatum.com#EXT#@contoso.com".
Для этого запроса необходимо задать для заголовка ConsistencyLevel значение eventual и $count=true строку запроса, так как запрос включает оператор endsWith. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
ПРИМЕЧАНИЕ: Зарезервированный символ "#" в значении userPrincipalName необходимо закодировать как "%23" в URL-адресе запроса. Дополнительные сведения см. в разделе Кодировка специальных символов.
GET https://graph.microsoft.com/beta/users?$select=id,displayName,mail,identities&$filter=endsWith(userPrincipalName,'%23EXT%23@contoso.com')&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string []{ "id","displayName","mail","identities" };
requestConfiguration.QueryParameters.Filter = "endsWith(userPrincipalName,'";
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestFilter := "endsWith(userPrincipalName,'"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Select: [] string {"id","displayName","mail","identities"},
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.select = new String []{"id", "displayName", "mail", "identities"};
requestConfiguration.queryParameters.filter = "endsWith(userPrincipalName,'";
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->select = ["id","displayName","mail","identities"];
$queryParameters->filter = "endsWith(userPrincipalName,'";
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Property "id,displayName,mail,identities" -Filter "endsWith(userPrincipalName,'" -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select = ["id","displayName","mail","identities"],
filter = "endsWith(userPrincipalName,'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(id,displayName,mail,identities)",
"@odata.count": 2,
"value": [
{
"id": "39807bd1-3dde-48f3-8165-81ddd4e46de0",
"displayName": "Adele Vance",
"mail": "AdeleV@adatum.com",
"identities": [
{
"signInType": "userPrincipalName",
"issuer": "contoso.com",
"issuerAssignedId": "AdeleV_adatum.com#EXT#@cntoso.com"
}
]
}
]
}
Пример 5. Перечисление времени последнего входа пользователей с определенным отображаемым именем
Запрос
Ниже показан пример запроса.
Примечание.
- Для сведений о свойстве signInActivity требуется лицензия Microsoft Entra ID P1 или P2 и
AuditLog.Read.All разрешение.
- При указании
$select=signInActivity или $filter=signInActivity при перечислении пользователей максимальный размер $top страницы составляет 500. Запросы с $top более чем 500 возвращаемыми страницами с до 500 пользователей. Свойство signInActivity поддерживает $filter (eq, , nenot, ge, ), leно не поддерживает другие фильтруемые свойства.
GET https://graph.microsoft.com/beta/users?$filter=startswith(displayName,'Eric')&$select=displayName,signInActivity
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "startswith(displayName,'Eric')";
requestConfiguration.QueryParameters.Select = new string []{ "displayName","signInActivity" };
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestFilter := "startswith(displayName,'Eric')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Select: [] string {"displayName","signInActivity"},
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "startswith(displayName,'Eric')";
requestConfiguration.queryParameters.select = new String []{"displayName", "signInActivity"};
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.filter('startswith(displayName,\'Eric\')')
.select('displayName,signInActivity')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->filter = "startswith(displayName,'Eric')";
$queryParameters->select = ["displayName","signInActivity"];
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Filter "startswith(displayName,'Eric')" -Property "displayName,signInActivity"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "startswith(displayName,'Eric')",
select = ["displayName","signInActivity"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/users?$filter=startswith(displayName,'Eric')&$select=displayName,signInActivity",
"value": [
{
"displayName": "Eric Solomon",
"signInActivity": {
"lastSignInDateTime": "2021-07-29T15:53:27Z",
"lastSignInRequestId": "f3149ee1-e347-4181-b45b-99a1f82b1c00",
"lastNonInteractiveSignInDateTime": "2021-07-29T17:53:42Z",
"lastNonInteractiveSignInRequestId": "868efa6a-b2e9-40e9-9b1c-0aaea5b50200",
"lastSuccessfulSignInDateTime": "",
"lastSuccessfulSignInRequestId": ""
}
}
]
}
Пример 6. Перечисление времени последнего входа пользователей в определенном диапазоне времени
Запрос
Ниже показан пример запроса.
Примечание.
Для сведений о свойстве signInActivity требуется лицензия Microsoft Entra ID P1 или P2 и AuditLog.Read.All разрешение.
GET https://graph.microsoft.com/beta/users?$filter=signInActivity/lastSignInDateTime le 2021-07-21T00:00:00Z
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/users?filter=signInActivity/lastSignInDateTime le 2021-07-21T00:00:00Z",
"value": [
{
"displayName": "Adele Vance",
"userPrincipalName": "AdeleV@contoso.com",
"signInActivity": {
"lastSignInDateTime": "2021-06-17T16:41:33Z",
"lastSignInRequestId": "d4d31c40-4c36-4775-ad59-7d1e6a171f00",
"lastNonInteractiveSignInDateTime": "0001-01-01T00:00:00Z",
"lastNonInteractiveSignInRequestId": "",
"lastSuccessfulSignInDateTime": "",
"lastSuccessfulSignInRequestId": ""
}
},
{
"displayName": "Alex Wilber",
"userPrincipalName": "AlexW@contoso.com",
"signInActivity": {
"lastSignInDateTime": "2021-07-29T15:53:27Z",
"lastSignInRequestId": "f3149ee1-e347-4181-b45b-99a1f82b1c00",
"lastNonInteractiveSignInDateTime": "2021-07-29T17:53:42Z",
"lastNonInteractiveSignInRequestId": "868efa6a-b2e9-40e9-9b1c-0aaea5b50200",
"lastSuccessfulSignInDateTime": "",
"lastSuccessfulSignInRequestId": ""
}
}
]
}
Пример 7. Получение только количества пользователей
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual, так как в запросе присутствует $count. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users/$count
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
await graphClient.Users.Count.GetAsync((requestConfiguration) =>
{
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
configuration := &graphusers.Users$countRequestBuilderGetRequestConfiguration{
Headers: headers,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
graphClient.Users().Count().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
graphClient.users().count().get(requestConfiguration -> {
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
const options = {
authProvider,
};
const client = Client.init(options);
let int32 = await client.api('/users/$count')
.version('beta')
.header('ConsistencyLevel','eventual')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\Count\CountRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new CountRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$graphServiceClient->users()->count()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUserCount -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.count.count_request_builder import CountRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_configuration = RequestConfiguration()
request_configuration.headers.add("ConsistencyLevel", "eventual")
await graph_client.users.count.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
HTTP/1.1 200 OK
Content-type: text/plain
893
Пример 8. Использование $filter и $top для получения одного пользователя с отображаемым именем, начинающимся с "a", включая количество возвращаемых объектов
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual и строка запроса $count=true, так как запрос содержит параметры запроса $orderby и $filter. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users?$filter=startswith(displayName,'a')&$orderby=displayName&$count=true&$top=1
ConsistencyLevel: eventual
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context":"https://graph.microsoft.com/beta/$metadata#users",
"@odata.count":1,
"value":[
{
"displayName":"a",
"mail":"a@contoso.com",
"mailNickname":"a_contoso.com#EXT#",
"otherMails":["a@contoso.com"],
"proxyAddresses":["SMTP:a@contoso.com"],
"userPrincipalName":"a_contoso.com#EXT#@contoso.com"
}
]
}
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual и строка запроса $count=true, так как запрос содержит параметры запроса $orderby и $filter, а также использует оператор endsWith. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users?$filter=endswith(mail,'a@contoso.com')&$orderby=userPrincipalName&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "endswith(mail,'a@contoso.com')";
requestConfiguration.QueryParameters.Orderby = new string []{ "userPrincipalName" };
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestFilter := "endswith(mail,'a@contoso.com')"
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Orderby: [] string {"userPrincipalName"},
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "endswith(mail,'a@contoso.com')";
requestConfiguration.queryParameters.orderby = new String []{"userPrincipalName"};
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.header('ConsistencyLevel','eventual')
.filter('endswith(mail,\'a@contoso.com\')')
.orderby('userPrincipalName')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->filter = "endswith(mail,'a@contoso.com')";
$queryParameters->orderby = ["userPrincipalName"];
$queryParameters->count = true;
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Filter "endswith(mail,'a@contoso.com')" -Sort "userPrincipalName" -CountVariable CountVar -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "endswith(mail,'a@contoso.com')",
orderby = ["userPrincipalName"],
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users",
"@odata.count": 1,
"value": [
{
"displayName": "Grady Archie",
"givenName": "Grady",
"jobTitle": "Designer",
"mail": "GradyA@contoso.com",
"userPrincipalName": "GradyA@contoso.com",
"id": "e8b753b5-4117-464e-9a08-713e1ff266b3"
}
]
}
Пример 10. Использование $search для получения пользователей с отображаемыми именами, содержащими буквы "wa", включая количество возвращаемых объектов
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual, так как в запросе присутствует $search. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users?$search="displayName:wa"&$orderby=displayName&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Search = "\"displayName:wa\"";
requestConfiguration.QueryParameters.Orderby = new string []{ "displayName" };
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestSearch := "\"displayName:wa\""
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Search: &requestSearch,
Orderby: [] string {"displayName"},
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.search = "\"displayName:wa\"";
requestConfiguration.queryParameters.orderby = new String []{"displayName"};
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.header('ConsistencyLevel','eventual')
.search('displayName:wa')
.orderby('displayName')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->search = "\"displayName:wa\"";
$queryParameters->orderby = ["displayName"];
$queryParameters->count = true;
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Search '"displayName:wa"' -Sort "displayName" -CountVariable CountVar -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
search = "\"displayName:wa\"",
orderby = ["displayName"],
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context":"https://graph.microsoft.com/beta/$metadata#users",
"@odata.count":7,
"value":[
{
"displayName":"Oscar Ward",
"givenName":"Oscar",
"mail":"oscarward@contoso.com",
"mailNickname":"oscward",
"userPrincipalName":"oscarward@contoso.com"
}
]
}
Пример 11. Использование $search для получения пользователей с отображаемыми именами, содержащими буквы "wa" или "ad", включая количество возвращенных объектов
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual, так как в запросе присутствует $search. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users?$search="displayName:wa" OR "displayName:ad"&$orderby=displayName&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Search = "\"displayName:wa\" OR \"displayName:ad\"";
requestConfiguration.QueryParameters.Orderby = new string []{ "displayName" };
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestSearch := "\"displayName:wa\" OR \"displayName:ad\""
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Search: &requestSearch,
Orderby: [] string {"displayName"},
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.search = "\"displayName:wa\" OR \"displayName:ad\"";
requestConfiguration.queryParameters.orderby = new String []{"displayName"};
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->search = "\"displayName:wa\" OR \"displayName:ad\"";
$queryParameters->orderby = ["displayName"];
$queryParameters->count = true;
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Search '"displayName:wa" OR "displayName:ad"' -Sort "displayName" -CountVariable CountVar -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
search = "\"displayName:wa\" OR \"displayName:ad\"",
orderby = ["displayName"],
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context":"https://graph.microsoft.com/beta/$metadata#users",
"@odata.count":7,
"value":[
{
"displayName":"Oscar Ward",
"givenName":"Oscar",
"mail":"oscarward@contoso.com",
"mailNickname":"oscward",
"userPrincipalName":"oscarward@contoso.com"
},
{
"displayName":"contosoAdmin1",
"mail":"'contosoadmin1@gmail.com",
"mailNickname":"contosoadmin1_gmail.com#EXT#",
"proxyAddresses":["SMTP:contosoadmin1@gmail.com"],
"userPrincipalName":"contosoadmin1_gmail.com#EXT#@contoso.com"
}
]
}
Пример 12. Использование $filter для получения пользователей, которым назначена определенная лицензия
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual, так как в запросе присутствует $search. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
Примечание. В настоящее время параметры $count и $search недоступны в клиентах Azure AD B2C.
GET https://graph.microsoft.com/beta/users?$select=id,mail,assignedLicenses&$filter=assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string []{ "id","mail","assignedLicenses" };
requestConfiguration.QueryParameters.Filter = "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)";
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestFilter := "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Select: [] string {"id","mail","assignedLicenses"},
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.select = new String []{"id", "mail", "assignedLicenses"};
requestConfiguration.queryParameters.filter = "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)";
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.filter('assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)')
.select('id,mail,assignedLicenses')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->select = ["id","mail","assignedLicenses"];
$queryParameters->filter = "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)";
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Property "id,mail,assignedLicenses" -Filter "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select = ["id","mail","assignedLicenses"],
filter = "assignedLicenses/any(u:u/skuId eq cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46)",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(id,mail,assignedLicenses)",
"value": [
{
"id": "cb4954e8-467f-4a6d-a8c8-28b9034fadbc",
"mail": "admin@contoso.com",
"assignedLicenses": [
{
"disabledPlans": [],
"skuId": "cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46"
}
]
},
{
"id": "81a133c2-bdf2-4e67-8755-7264366b04ee",
"mail": "DebraB@contoso.com",
"assignedLicenses": [
{
"disabledPlans": [],
"skuId": "cbdc14ab-d96c-4c30-b9f4-6ada7cdc1d46"
}
]
}
]
}
Пример 13. Получение значения расширения схемы для всех пользователей
В этом примере идентификатор расширения схемы — ext55gb1l09_msLearnCourses.
Запрос
GET https://graph.microsoft.com/beta/users?$select=ext55gb1l09_msLearnCourses
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string []{ "ext55gb1l09_msLearnCourses" };
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Select: [] string {"ext55gb1l09_msLearnCourses"},
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.select = new String []{"ext55gb1l09_msLearnCourses"};
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.select('ext55gb1l09_msLearnCourses')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->select = ["ext55gb1l09_msLearnCourses"];
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Property "ext55gb1l09_msLearnCourses"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select = ["ext55gb1l09_msLearnCourses"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
В следующем отклике свойство расширения ext55gb1l09_msLearnCourses схемы не назначено в двух объектах пользователя.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(ext55gb1l09_msLearnCourses)",
"value": [
{},
{
"ext55gb1l09_msLearnCourses": {
"@odata.type": "#microsoft.graph.ComplexExtensionValue",
"courseType": "Developer",
"courseName": "Introduction to Microsoft Graph",
"courseId": 1
}
},
{}
]
}
Примечание. Также можно применить $filter к свойству расширения схемы, чтобы получить объекты, в которых свойство в коллекции соответствует указанному значению. Используется следующий синтаксис: /users?$filter={schemaPropertyID}/{propertyName} eq 'value'. Например, GET /users?$select=ext55gb1l09_msLearnCourses&$filter=ext55gb1l09_msLearnCourses/courseType eq 'Developer'. Поддерживаемые операторы: eq и not.
Пример 14. Перечисление всех пользователей с пользовательским назначением атрибута безопасности, равным значению
В следующем примере показано, как вывести список всех пользователей с пользовательским назначением атрибута безопасности, равным значению. В этом примере извлекаются пользователи с настраиваемым атрибутом AppCountry безопасности со значением , равным Canada. Значение фильтра учитывает регистр. Необходимо добавить ConsistencyLevel=eventual в запрос или заголовок. Необходимо также включить, $count=true чтобы убедиться, что запрос маршрутизируется правильно.
Пользователь No 1
- Набор атрибутов:
Marketing
- Атрибут:
AppCountry
- Тип данных атрибута: коллекция строк
- Значение атрибута:
["India","Canada"]
Пользователь No 2
- Набор атрибутов:
Marketing
- Атрибут:
AppCountry
- Тип данных атрибута: коллекция строк
- Значение атрибута:
["Canada","Mexico"]
Чтобы получить назначения настраиваемых атрибутов безопасности, вызывающему субъекту должна быть назначена роль читателя назначения атрибутов или администратора назначения атрибутов, а также должно быть предоставлено разрешение CustomSecAttributeAssignment.Read.All или CustomSecAttributeAssignment.ReadWrite.All.
Примеры назначений настраиваемых атрибутов безопасности см. в разделе Примеры. Назначение, обновление, перечисление или удаление назначений настраиваемых атрибутов безопасности с помощью API Graph Майкрософт.
Запрос
GET https://graph.microsoft.com/beta/users?$count=true&$select=id,displayName,customSecurityAttributes&$filter=customSecurityAttributes/Marketing/AppCountry eq 'Canada'
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.QueryParameters.Select = new string []{ "id","displayName","customSecurityAttributes" };
requestConfiguration.QueryParameters.Filter = "customSecurityAttributes/Marketing/AppCountry eq 'Canada'";
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestCount := true
requestFilter := "customSecurityAttributes/Marketing/AppCountry eq 'Canada'"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Count: &requestCount,
Select: [] string {"id","displayName","customSecurityAttributes"},
Filter: &requestFilter,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.count = true;
requestConfiguration.queryParameters.select = new String []{"id", "displayName", "customSecurityAttributes"};
requestConfiguration.queryParameters.filter = "customSecurityAttributes/Marketing/AppCountry eq 'Canada'";
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.header('ConsistencyLevel','eventual')
.filter('customSecurityAttributes/Marketing/AppCountry eq \'Canada\'')
.select('id,displayName,customSecurityAttributes')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->count = true;
$queryParameters->select = ["id","displayName","customSecurityAttributes"];
$queryParameters->filter = "customSecurityAttributes/Marketing/AppCountry eq 'Canada'";
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -CountVariable CountVar -Property "id,displayName,customSecurityAttributes" -Filter "customSecurityAttributes/Marketing/AppCountry eq 'Canada'" -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
count = True,
select = ["id","displayName","customSecurityAttributes"],
filter = "customSecurityAttributes/Marketing/AppCountry eq 'Canada'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
HTTP/1.1 200 OK
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(id,displayName,customSecurityAttributes)",
"@odata.count": 2,
"value": [
{
"id": "dbaf3778-4f81-4ea0-ac1c-502a293c12ac",
"displayName": "Jiya",
"customSecurityAttributes": {
"Engineering": {
"@odata.type": "#microsoft.graph.customSecurityAttributeValue",
"Datacenter@odata.type": "#Collection(String)",
"Datacenter": [
"India"
]
},
"Marketing": {
"@odata.type": "#microsoft.graph.customSecurityAttributeValue",
"AppCountry@odata.type": "#Collection(String)",
"AppCountry": [
"India",
"Canada"
],
"EmployeeId": "KX19476"
}
}
},
{
"id": "6bac433c-48c6-4213-a316-1428de32701b",
"displayName": "Jana",
"customSecurityAttributes": {
"Marketing": {
"@odata.type": "#microsoft.graph.customSecurityAttributeValue",
"AppCountry@odata.type": "#Collection(String)",
"AppCountry": [
"Canada",
"Mexico"
],
"EmployeeId": "GS46982"
}
}
}
]
}
Пример 15. Перечисление всех пользователей, управление которыми ограничено
В следующем примере показано, как получить список всех пользователей, управление которыми ограничено.
Запрос
Ниже показан пример запроса.
GET https://graph.microsoft.com/beta/users?$filter=isManagementRestricted eq true&$select=displayName,userPrincipalName
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "isManagementRestricted eq true";
requestConfiguration.QueryParameters.Select = new string []{ "displayName","userPrincipalName" };
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestFilter := "isManagementRestricted eq true"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Select: [] string {"displayName","userPrincipalName"},
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "isManagementRestricted eq true";
requestConfiguration.queryParameters.select = new String []{"displayName", "userPrincipalName"};
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.filter('isManagementRestricted eq true')
.select('displayName,userPrincipalName')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->filter = "isManagementRestricted eq true";
$queryParameters->select = ["displayName","userPrincipalName"];
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Filter "isManagementRestricted eq true" -Property "displayName,userPrincipalName"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "isManagementRestricted eq true",
select = ["displayName","userPrincipalName"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(displayName,userPrincipalName)",
"value": [
{
"displayName": "Adele",
"userPrincipalName": "Adele@contoso.com"
},
{
"displayName": "Bob",
"userPrincipalName": "Bob@contoso.com"
}
]
}
Пример 16. Использование $filter и endsWith для получения пользователей с указанным доменом верхнего уровня в otherMails
Запрос
Ниже показан пример запроса. Для этого запроса требуется заголовок ConsistencyLevel с присвоенным значением eventual, так как в запросе присутствует $count. Дополнительные сведения об использовании ConsistencyLevel и $countсм. в разделе Дополнительные возможности запросов к объектам каталога.
GET https://graph.microsoft.com/beta/users?$filter=otherMails/any(x:endswith(x,'.edu'))&$count=true
ConsistencyLevel: eventual
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "otherMails/any(x:endswith(x,'.edu'))";
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.Headers.Add("ConsistencyLevel", "eventual");
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
abstractions "github.com/microsoft/kiota-abstractions-go"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
headers := abstractions.NewRequestHeaders()
headers.Add("ConsistencyLevel", "eventual")
requestFilter := "otherMails/any(x:endswith(x,'.edu'))"
requestCount := true
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Count: &requestCount,
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
Headers: headers,
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "otherMails/any(x:endswith(x,'.edu'))";
requestConfiguration.queryParameters.count = true;
requestConfiguration.headers.add("ConsistencyLevel", "eventual");
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.header('ConsistencyLevel','eventual')
.filter('otherMails/any(x:endswith(x,\'.edu\'))')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$headers = [
'ConsistencyLevel' => 'eventual',
];
$requestConfiguration->headers = $headers;
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->filter = "otherMails/any(x:endswith(x,'.edu'))";
$queryParameters->count = true;
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -Filter "otherMails/any(x:endswith(x,'.edu'))" -CountVariable CountVar -ConsistencyLevel eventual
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
filter = "otherMails/any(x:endswith(x,'.edu'))",
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
request_configuration.headers.add("ConsistencyLevel", "eventual")
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users",
"@odata.nextLink": "https://graph.microsoft.com/beta/users?$filter=otherMails%2fany(x%3aendswith(x%2c%27.edu%27))&$skiptoken=m~AQAoOzAzNWVkMDQ1MTE5ZjRlMmNiM2Y2ODQzMmM4YzNiOWJiOzswOzA7Ow",
"@microsoft.graph.tips": "Use $select to choose only the properties your app needs, as this can lead to performance improvements. For example: GET users?$select=signInActivity,cloudLicensing",
"value": [
{
"displayName": "Isaiah Langer",
"mail": "isaiahl@fineartschool.edu",
"id": "0012cd20-3890-409e-9db3-afc3055ebe22"
},
{
"displayName": "Adele Vance",
"mail": "adelev@bellowscollege.edu",
"id": "0012cd20-3890-409e-9db3-afc3055ebe22"
}
]
}
Пример 17. Вывод списка всех пользователей, не являющихся агентами, и отображение только отображаемого имени пользователей
Запрос
Ниже показан пример запроса.
GET https://graph.microsoft.com/beta/users?$count=true&$filter=not isof('microsoft.graph.agentUser')&$select=displayName
// Code snippets are only available for the latest version. Current version is 5.x
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Users.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Count = true;
requestConfiguration.QueryParameters.Filter = "not isof('microsoft.graph.agentUser')";
requestConfiguration.QueryParameters.Select = new string []{ "displayName" };
});
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-beta-sdk-go/users"
//other-imports
)
requestCount := true
requestFilter := "not isof('microsoft.graph.agentUser')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Count: &requestCount,
Filter: &requestFilter,
Select: [] string {"displayName"},
}
configuration := &graphusers.UsersRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
users, err := graphClient.Users().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
UserCollectionResponse result = graphClient.users().get(requestConfiguration -> {
requestConfiguration.queryParameters.count = true;
requestConfiguration.queryParameters.filter = "not isof('microsoft.graph.agentUser')";
requestConfiguration.queryParameters.select = new String []{"displayName"};
});
const options = {
authProvider,
};
const client = Client.init(options);
let users = await client.api('/users')
.version('beta')
.filter('not isof(\'microsoft.graph.agentUser\')')
.select('displayName')
.get();
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Users\UsersRequestBuilderGetRequestConfiguration;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestConfiguration = new UsersRequestBuilderGetRequestConfiguration();
$queryParameters = UsersRequestBuilderGetRequestConfiguration::createQueryParameters();
$queryParameters->count = true;
$queryParameters->filter = "not isof('microsoft.graph.agentUser')";
$queryParameters->select = ["displayName"];
$requestConfiguration->queryParameters = $queryParameters;
$result = $graphServiceClient->users()->get($requestConfiguration)->wait();
Import-Module Microsoft.Graph.Beta.Users
Get-MgBetaUser -CountVariable CountVar -Filter "not isof('microsoft.graph.agentUser')" -Property "displayName"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.users.users_request_builder import UsersRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
query_params = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
count = True,
filter = "not isof('microsoft.graph.agentUser')",
select = ["displayName"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Отклик
Ниже показан пример отклика.
Примечание. Объект отклика, показанный здесь, может быть сокращен для удобочитаемости.
HTTP/1.1 200 OK
Content-Type: application/json
{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users(displayName)",
"@odata.count": 3,
"value": [
{
"displayName": "Adrian Smith",
"id": "04b9f5a2-ee41-4d0e-b500-8de414d178c9"
},
{
"displayName": "Lewis Richardson",
"id": "0d03514d-35b0-4ffd-9ed9-d8052757e1c4"
},
{
"displayName": "Fung Lu",
"id": "146f9fcb-64c9-4b6e-b92f-bd4892fabdcd"
}
]
}