Usar parâmetros de consulta para personalizar respostas
Artigo
O Microsoft Graph suporta parâmetros de consulta que pode utilizar para especificar e controlar a quantidade de dados devolvidos numa resposta. O suporte para os parâmetros de consulta exatos varia de uma operação de API para outra e, dependendo da API, pode diferir entre os pontos finais v1.0 e beta .
Dica
No ponto final beta , o $ prefixo é opcional. Por exemplo, em vez de $filter, você pode usar filter.
No ponto final v1.0 , o $ prefixo é opcional apenas para um subconjunto de APIs.
Para simplificar, inclua $ sempre em todas as versões.
Uma operação de API do Microsoft Graph pode oferecer suporte a uma ou mais das seguintes opções de consulta de sistema OData. Estas opções de consulta são compatíveis com a linguagem de consulta OData V4 e são suportadas apenas em operações GET.
Indexa num conjunto de resultados. Também utilizado por algumas APIs para implementar paginação e pode ser utilizado em conjunto com $top para páginar resultados manualmente.
Para saber as opções de consulta do sistema OData que uma API e as respetivas propriedades suportam, veja a tabela "Propriedades" na página de recursos e a secção "Parâmetros de consulta opcionais" das operações LIST e GET para a API.
Os valores dos parâmetros de consulta devem ser codificados por percentagem de acordo com RFC 3986. Por exemplo, todos os carateres reservados nas cadeias de consulta têm de estar codificados por percentagem. Muitos clientes HTTP, browsers e ferramentas (como o Explorador do Graph) processam esta codificação por si. Se uma consulta falhar, uma causa possível é a falha ao codificar adequadamente os valores dos parâmetros de consulta. Em alguns casos, tem de codificar novamente os valores.
GET https://graph.microsoft.com/v1.0/users?$filter=startswith(givenName, 'J')
// 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(givenName, 'J')";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "startswith(givenName, 'J')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
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.filter = "startswith(givenName, 'J')";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.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(givenName, 'J')",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
GET https://graph.microsoft.com/v1.0/users?$filter=startswith(givenName%2C+'J')
// 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(givenName, 'J')";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "startswith(givenName, 'J')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
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.filter = "startswith(givenName, 'J')";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.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(givenName, 'J')",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
GET https://graph.microsoft.com/v1.0/users?$filter=startswith%28givenName%2C%20%27J%27%29
// 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(givenName, 'J')";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "startswith(givenName, 'J')"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
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.filter = "startswith(givenName, 'J')";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.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(givenName, 'J')",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Para pedidos que utilizem plicas, se os valores de parâmetros também contiverem plicas, têm de ser escape duplos; caso contrário, o pedido falha devido a sintaxe inválida. No exemplo, o valor de cadeia de caracteres let''s meet for lunch? tem o escape de aspas simples.
GET https://graph.microsoft.com/v1.0/me/messages?$filter=subject eq 'let''s meet for lunch?'
// 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.Me.Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "subject eq 'let''s meet for lunch?'";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "subject eq 'let''s meet for lunch?'"
requestParameters := &graphusers.ItemMessagesRequestBuilderGetQueryParameters{
Filter: &requestFilter,
}
configuration := &graphusers.ItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "subject eq 'let''s meet for lunch?'";
});
Import-Module Microsoft.Graph.Mail
# A UPN can also be used as -UserId.
Get-MgUserMessage -UserId $userId -Filter "subject eq 'let''s meet for lunch?'"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
filter = "subject eq 'let''s meet for lunch?'",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
Use o $count parâmetro de consulta para recuperar a contagem do número total de itens em uma coleção ou correspondência de uma expressão.
$count pode ser usado das seguintes maneiras:
Como parâmetro de cadeia de consulta com a sintaxe $count=true para incluir uma contagem do número total de itens numa coleção juntamente com a página de valores de dados devolvidos pelo Microsoft Graph. Por exemplo, users?$count=true.
Como um segmento de URL para recuperar somente o total inteiro da coleção. Por exemplo, users/$count.
Não há suporte para o uso de $count em locatários do Microsoft Azure Active Directory B2C.
Por exemplo, o pedido seguinte devolve a coleção de contactos do utilizador atual e o número de itens na coleção de contactos numa propriedade @odata.count .
GET https://graph.microsoft.com/v1.0/me/contacts?$count=true
// 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.Me.Contacts.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Count = true;
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestCount := true
requestParameters := &graphusers.ItemContactsRequestBuilderGetQueryParameters{
Count: &requestCount,
}
configuration := &graphusers.ItemContactsRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
contacts, err := graphClient.Me().Contacts().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
ContactCollectionResponse result = graphClient.me().contacts().get(requestConfiguration -> {
requestConfiguration.queryParameters.count = true;
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.contacts.contacts_request_builder import ContactsRequestBuilder
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 = ContactsRequestBuilder.ContactsRequestBuilderGetQueryParameters(
count = True,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.contacts.get(request_configuration = request_configuration)
Para objetos de diretório, ou seja, recursos que derivam de directoryObject, o $count parâmetro de consulta só é suportado em consultas avançadas.
parâmetro expand
Muitos recursos do Microsoft Graph expõem as propriedades declaradas do recurso e as relações delas com outros recursos. Essas relações também são chamadas de propriedades de referência ou propriedades de navegação e podem fazer referência a um único recurso ou a uma coleção de recursos. Por exemplo, as pastas de email, gerente e subordinados diretos de um usuário são todas expostas como relações.
Você pode usar o parâmetro de cadeia de caracteres de consulta $expand para incluir o recurso expandido ou a coleção referenciada por uma única relação (propriedade de navegação) em seus resultados. Para algumas APIs, apenas uma relação pode ser expandida num único pedido.
O exemplo a seguir obtém informações da unidade raiz juntamente com os itens filho de nível superior em uma unidade:
GET https://graph.microsoft.com/v1.0/me/drive/root?$expand=children
// 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.Drives["{drive-id}"].Root.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Expand = new string []{ "children" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphdrives "github.com/microsoftgraph/msgraph-sdk-go/drives"
//other-imports
)
requestParameters := &graphdrives.ItemRootRequestBuilderGetQueryParameters{
Expand: [] string {"children"},
}
configuration := &graphdrives.ItemRootRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
root, err := graphClient.Drives().ByDriveId("drive-id").Root().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
DriveItem result = graphClient.drives().byDriveId("{drive-id}").root().get(requestConfiguration -> {
requestConfiguration.queryParameters.expand = new String []{"children"};
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.drives.item.root.root_request_builder import RootRequestBuilder
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 = RootRequestBuilder.RootRequestBuilderGetQueryParameters(
expand = ["children"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.drives.by_drive_id('drive-id').root.get(request_configuration = request_configuration)
Com algumas coleções de recursos, também pode especificar as propriedades a devolver nos recursos expandidos ao adicionar um $select parâmetro. O exemplo seguinte executa a mesma consulta que o exemplo anterior, mas utiliza uma $select instrução para limitar as propriedades devolvidas para os itens subordinados expandidos às propriedades do ID e do nome .
GET https://graph.microsoft.com/v1.0/me/drive/root?$expand=children($select=id,name)
// 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.Drives["{drive-id}"].Root.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Expand = new string []{ "children($select=id,name)" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphdrives "github.com/microsoftgraph/msgraph-sdk-go/drives"
//other-imports
)
requestParameters := &graphdrives.ItemRootRequestBuilderGetQueryParameters{
Expand: [] string {"children($select=id,name)"},
}
configuration := &graphdrives.ItemRootRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
root, err := graphClient.Drives().ByDriveId("drive-id").Root().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
DriveItem result = graphClient.drives().byDriveId("{drive-id}").root().get(requestConfiguration -> {
requestConfiguration.queryParameters.expand = new String []{"children($select=id,name)"};
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.drives.item.root.root_request_builder import RootRequestBuilder
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 = RootRequestBuilder.RootRequestBuilderGetQueryParameters(
expand = ["children($select=id,name)"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.drives.by_drive_id('drive-id').root.get(request_configuration = request_configuration)
Nem todas as relações e recursos dão suporte ao parâmetro de consulta $expand. Por exemplo, você pode expandir as relações directReports, manager e memberOf em um usuário, mas não pode expandir seus relacionamentos de eventos, mensagens ou foto. Nem todos os recursos ou relações dão suporte ao uso de $select em itens expandidos.
GET https://graph.microsoft.com/v1.0/users?$format=json
// 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.Format = "json";
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFormat := "json"
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Format: &requestFormat,
}
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.format = "json";
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.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(
format = "json",
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
O $format parâmetro de consulta suporta vários formatos (por exemplo, atom, xmle json) mas os resultados podem não ser devolvidos em todos os formatos.
parâmetro orderby
Use o parâmetro de consulta $orderby para especificar a ordem de classificação dos itens retornados pelo Microsoft Graph. A ordem padrão é ordem crescente.
Por exemplo, o pedido seguinte devolve os utilizadores na organização ordenados pelo respetivo nome a apresentar por ordem ascendente:
GET https://graph.microsoft.com/v1.0/users?$orderby=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.Orderby = new string []{ "displayName" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestParameters := &graphusers.UsersRequestBuilderGetQueryParameters{
Orderby: [] 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.orderby = new String []{"displayName"};
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.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(
orderby = ["displayName"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.users.get(request_configuration = request_configuration)
Algumas APIs suportam a ordenação por entidades de tipo complexo. O pedido seguinte obtém mensagens e ordena-as pelo campo de endereço da propriedade from , que é do tipo complexo emailAddress:
GET https://graph.microsoft.com/v1.0/me/messages?$orderby=from/emailAddress/address
// 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.Me.Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Orderby = new string []{ "from/emailAddress/address" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestParameters := &graphusers.ItemMessagesRequestBuilderGetQueryParameters{
Orderby: [] string {"from/emailAddress/address"},
}
configuration := &graphusers.ItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.orderby = new String []{"from/emailAddress/address"};
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
orderby = ["from/emailAddress/address"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
Para ordenar os resultados por ordem ascendente ou descendente, acrescente ou ascdesc ao nome do campo, separados por um espaço; por exemplo, ?$orderby=name desc (não codificado), ?$orderby=name%20desc (codificado por URL). Se a sequência de ordenação não for especificada, a ordem ascendente predefinida é inferida.
Com algumas APIs, você pode ordenar os resultados em várias propriedades. Por exemplo, a solicitação a seguir ordena as mensagens na caixa de entrada do usuário primeiro pelo nome da pessoa que enviou, em ordem decrescente (Z – A) e, em seguida, por assunto, em ordem ascendente (padrão).
GET https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/messages?$orderby=from/emailAddress/name desc,subject
// 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.Me.MailFolders["{mailFolder-id}"].Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Orderby = new string []{ "from/emailAddress/name desc","subject" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestParameters := &graphusers.MailFoldersItemMessagesRequestBuilderGetQueryParameters{
Orderby: [] string {"from/emailAddress/name desc","subject"},
}
configuration := &graphusers.MailFoldersItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().MailFolders().ByMailFolderId("mailFolder-id").Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().mailFolders().byMailFolderId("{mailFolder-id}").messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.orderby = new String []{"from/emailAddress/name desc", "subject"};
});
Import-Module Microsoft.Graph.Mail
# A UPN can also be used as -UserId.
Get-MgUserMailFolderMessage -UserId $userId -MailFolderId $mailFolderId -Sort "from/emailAddress/name desc,subject"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.mail_folders.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
orderby = ["from/emailAddress/name desc","subject"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.mail_folders.by_mail_folder_id('mailFolder-id').messages.get(request_configuration = request_configuration)
Quando especificar $filter, o serviço infere uma sequência de ordenação para os resultados. Se você usar $orderby e $filter juntos para receber mensagens, como o servidor sempre infere uma ordem de classificação para os resultados de $filter, você deve especificar propriedades de determinadas maneiras.
O exemplo a seguir mostra uma consulta filtrada pelas propriedades subject e priority e classificadas pelas propriedades subject, priority e receivedDateTime em ordem decrescente.
GET https://graph.microsoft.com/v1.0/me/messages?$filter=Subject eq 'welcome' and importance eq 'normal'&$orderby=subject,importance,receivedDateTime desc
// 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.Me.Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Filter = "Subject eq 'welcome' and importance eq 'normal'";
requestConfiguration.QueryParameters.Orderby = new string []{ "subject","importance","receivedDateTime desc" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestFilter := "Subject eq 'welcome' and importance eq 'normal'"
requestParameters := &graphusers.ItemMessagesRequestBuilderGetQueryParameters{
Filter: &requestFilter,
Orderby: [] string {"subject","importance","receivedDateTime desc"},
}
configuration := &graphusers.ItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.filter = "Subject eq 'welcome' and importance eq 'normal'";
requestConfiguration.queryParameters.orderby = new String []{"subject", "importance", "receivedDateTime desc"};
});
Import-Module Microsoft.Graph.Mail
# A UPN can also be used as -UserId.
Get-MgUserMessage -UserId $userId -Filter "Subject eq 'welcome' and importance eq 'normal'" -Sort "subject,importance,receivedDateTime desc"
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
filter = "Subject eq 'welcome' and importance eq 'normal'",
orderby = ["subject","importance","receivedDateTime desc"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
Use o parâmetro de consulta $search para restringir os resultados de uma solicitação para corresponder a um critério de pesquisa. Sua sintaxe e comportamento variam de uma operação de API para outra. Para ver a sintaxe para $search em diferentes recursos, consulte Usar o parâmetro de consulta $search para corresponder a um critério de pesquisa.
parâmetro select
Utilize o $select parâmetro de consulta para devolver um subconjunto de propriedades de um recurso. Com $select, você pode especificar um subconjunto ou um superconjunto das propriedades padrão.
Quando faz um pedido GET sem utilizar $select para limitar a quantidade de dados de propriedades, o Microsoft Graph inclui uma propriedade @microsoft.graph.tips que fornece uma recomendação de melhores práticas para utilizar $select semelhante à seguinte mensagem:
"@microsoft.graph.tips": "Use $select to choose only the properties your app needs, as this can lead to performance improvements. For example: GET groups?$select=appMetadata,assignedLabels",
Por exemplo, ao recuperar as mensagens do usuário conectado, você pode especificar que somente as propriedades from e subject sejam retornadas:
GET https://graph.microsoft.com/v1.0/me/messages?$select=from,subject
// 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.Me.Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Select = new string []{ "from","subject" };
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestParameters := &graphusers.ItemMessagesRequestBuilderGetQueryParameters{
Select: [] string {"from","subject"},
}
configuration := &graphusers.ItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.select = new String []{"from", "subject"};
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
select = ["from","subject"],
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
Em geral, recomendamos que você use $select para limitar as propriedades retornadas por uma consulta àqueles exigidas pelo aplicativo. Isso se aplica particularmente a consultas com o potencial de retornar um conjunto de resultados amplo. Limitar as propriedades retornadas em cada linha reduzirá a carga de rede e ajudará a melhorar o desempenho do aplicativo.
Na v1.0, alguns recursos do Microsoft Entra que derivam de directoryObject, como utilizador e grupo, devolvem um subconjunto limitado e predefinido de propriedades nas leituras. Para estes recursos, tem de utilizar $select para devolver propriedades fora do conjunto predefinido.
parâmetro skip
Utilize o $skip parâmetro de consulta para definir o número de itens a ignorar no início de uma coleção.
Por exemplo, o pedido seguinte devolve eventos para o utilizador ordenados por data criada, começando pelo 21º evento na coleção:
GET https://graph.microsoft.com/v1.0/me/events?$orderby=createdDateTime&$skip=20
// 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.Me.Events.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Orderby = new string []{ "createdDateTime" };
requestConfiguration.QueryParameters.Skip = 20;
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestSkip := int32(20)
requestParameters := &graphusers.ItemEventsRequestBuilderGetQueryParameters{
Orderby: [] string {"createdDateTime"},
Skip: &requestSkip,
}
configuration := &graphusers.ItemEventsRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
events, err := graphClient.Me().Events().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
EventCollectionResponse result = graphClient.me().events().get(requestConfiguration -> {
requestConfiguration.queryParameters.orderby = new String []{"createdDateTime"};
requestConfiguration.queryParameters.skip = 20;
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.events.events_request_builder import EventsRequestBuilder
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 = EventsRequestBuilder.EventsRequestBuilderGetQueryParameters(
orderby = ["createdDateTime"],
skip = 20,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.events.get(request_configuration = request_configuration)
Algumas APIs do Microsoft Graph, como Email e Calendário do Outlook (mensagem, evento e calendário), usam $skip para implementar a paginação. Quando os resultados de uma consulta abrangem várias páginas, estas APIs devolvem uma propriedade @odata.nextLink com um URL que contém um $skip parâmetro. Você pode usar essa URL para retornar a próxima página de resultados. Para saber mais, confira Paginação.
Algumas solicitações retornam várias páginas de dados, devido à paginação do lado do servidor ou devido ao uso do parâmetro $top para limitar o tamanho da página da resposta. Muitas APIs do Microsoft Graph usam o parâmetro de consulta skipToken para fazer referência a páginas subsequentes do resultado.
Este parâmetro contém um token opaco que referencia a página seguinte dos resultados e é devolvido no URL fornecido na propriedade @odata.nextLink na resposta. Para saber mais, confira Paginação.
Observação
Se você estiver usando a OData Count (adicionando $count=true na cadeia de caracteres de consulta) para consultas em objetos de diretório, a propriedade @odata.count estará presente apenas na primeira página.
O cabeçalho consistencyLevel necessário para consultas avançadas em objetos de diretório não está incluído por padrão em solicitações de página subsequentes. Ele deve ser definido explicitamente nas páginas subsequentes.
parâmetro top
Utilize o $top parâmetro de consulta para especificar o número de itens a incluir no resultado.
Se mais itens permanecerem no conjunto de resultados, o corpo da resposta contém um parâmetro @odata.nextLink . Esse parâmetro contém uma URL que você pode usar para obter a próxima página de resultados. Para saber mais, confira Paginação.
O valor mínimo de $top é 1 e o máximo depende da API correspondente.
Por exemplo, a seguinte solicitação de lista de mensagens retorna as cinco primeiras mensagens na caixa de correio do usuário:
GET https://graph.microsoft.com/v1.0/me/messages?$top=5
// 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.Me.Messages.GetAsync((requestConfiguration) =>
{
requestConfiguration.QueryParameters.Top = 5;
});
// Code snippets are only available for the latest major version. Current major version is $v1.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
graphusers "github.com/microsoftgraph/msgraph-sdk-go/users"
//other-imports
)
requestTop := int32(5)
requestParameters := &graphusers.ItemMessagesRequestBuilderGetQueryParameters{
Top: &requestTop,
}
configuration := &graphusers.ItemMessagesRequestBuilderGetRequestConfiguration{
QueryParameters: requestParameters,
}
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
messages, err := graphClient.Me().Messages().Get(context.Background(), configuration)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
MessageCollectionResponse result = graphClient.me().messages().get(requestConfiguration -> {
requestConfiguration.queryParameters.top = 5;
});
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph import GraphServiceClient
from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
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 = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
top = 5,
)
request_configuration = RequestConfiguration(
query_parameters = query_params,
)
result = await graph_client.me.messages.get(request_configuration = request_configuration)
O cabeçalho consistencyLevel necessário para consultas avançadas em objetos de diretório não está incluído por padrão em solicitações de página subsequentes. Ele deve ser definido explicitamente nas páginas subsequentes.
Tratamento de erro para parâmetros de consulta
Alguns pedidos devolvem uma mensagem de erro se não for suportado um parâmetro de consulta especificado. Por exemplo, não pode utilizar $expand na user/photo relação.
https://graph.microsoft.com/v1.0/me?$expand=photo
{
"error":{
"code":"ExpandNotSupported",
"message":"Expand is not allowed for property 'Photo' according to the entity schema.",
"innerError":{
"request-id":"1653fefd-bc31-484b-bb10-8dc33cb853ec",
"date":"2017-07-31T20:55:01"
}
}
}
No entanto, por vezes, os parâmetros de consulta especificados num pedido falham silenciosamente. Por exemplo, para parâmetros de consulta não suportados e para combinações não suportadas de parâmetros de consulta. Nesses casos, você deve examinar os dados retornados pela solicitação para determinar se os parâmetros de consulta que especificou tiveram o efeito desejado.