Upravit

Sdílet prostřednictvím


Make API calls using the Microsoft Graph SDKs

The Microsoft Graph SDK service libraries provide a client class to use as the starting point for creating all API requests. There are two styles of client class: one uses a fluent interface to create the request (for example, client.Users["user-id"].Manager) and the other accepts a path string (for example, api("/users/user-id/manager")). When you have a request object, you can specify various options, such as filtering and sorting, and finally, you select the type of operation you want to perform.

There's also the Microsoft Graph PowerShell SDK, which has no client class. Instead, all requests are represented as PowerShell commands. For example, to get a user's manager, the command is Get-MgUserManager. For more information on finding commands for API calls, see Navigating the Microsoft Graph PowerShell SDK.

Read information from Microsoft Graph

To read information from Microsoft Graph, you first need to create a request object and then run the GET method on the request.

// GET https://graph.microsoft.com/v1.0/me
var user = await graphClient.Me
    .GetAsync();

Use $select to control the properties returned

When retrieving an entity, not all properties are automatically retrieved; sometimes, they need to be explicitly selected. Also, returning the default set of properties isn't necessary in some scenarios. Selecting just the required properties can improve the performance of the request. You can customize the request to include the $select query parameter with a list of properties.

// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
var user = await graphClient.Me
    .GetAsync(requestConfiguration =>
    {
        requestConfiguration.QueryParameters.Select =
            ["displayName", "jobTitle"];
    });

Retrieve a list of entities

Retrieving a list of entities is similar to retrieving a single entity, except other options exist for configuring the request. The $filter query parameter can reduce the result set to only those rows that match the provided condition. The $orderby query parameter requests that the server provide the list of entities sorted by the specified properties.

Note

Some requests for Microsoft Entra resources require the use of advanced query capabilities. If you get a response indicating a bad request, unsupported query, or a response that includes unexpected results, including the $count query parameter and ConsistencyLevel header may allow the request to succeed. For details and examples, see Advanced query capabilities on directory objects.

// GET https://graph.microsoft.com/v1.0/me/messages?
// $select=subject,sender&$filter=subject eq 'Hello world'
var messages = await graphClient.Me.Messages
    .GetAsync(requestConfig =>
    {
        requestConfig.QueryParameters.Select =
            ["subject", "sender"];
        requestConfig.QueryParameters.Filter =
            "subject eq 'Hello world'";
    });

The object returned when retrieving a list of entities will likely be a paged collection. For details about how to get the complete list of entities, see paging through a collection.

Access an item of a collection

For SDKs that support a fluent style, collections of entities can be accessed using an array index. For template-based SDKs, it's sufficient to embed the item identifier in the path segment following the collection. For PowerShell, identifiers are passed as parameters.

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
var message = await graphClient.Me.Messages[messageId]
    .GetAsync();

You can use the $expand filter to request a related entity or collection of entities at the same time that you request the main entity.

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
// messageId is a string containing the id property of the message
var message = await graphClient.Me.Messages[messageId]
    .GetAsync(requestConfig =>
        requestConfig.QueryParameters.Expand =
            ["attachments"]);

Delete an entity

Delete requests are constructed in the same way as requests to retrieve an entity, but use a DELETE request instead of a GET.

// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
await graphClient.Me.Messages[messageId]
    .DeleteAsync();

Creating a new entity with POST

For fluent style and template-based SDKs, new items can be added to collections with a POST method. For PowerShell, a New-* command accepts parameters that map to the entity to add. The created entity is returned from the call.

// POST https://graph.microsoft.com/v1.0/me/calendars
var calendar = new Calendar
{
    Name = "Volunteer",
};

var newCalendar = await graphClient.Me.Calendars
    .PostAsync(calendar);

Updating an existing entity with PATCH

Most updates in Microsoft Graph are performed using a PATCH method; therefore, it's only necessary to include the properties you want to change in the object you pass.

// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
var team = new Team
{
    FunSettings = new TeamFunSettings
    {
        AllowGiphy = true,
        GiphyContentRating = GiphyRatingType.Strict,
    },
};

// teamId is a string containing the id property of the team
await graphClient.Teams[teamId]
    .PatchAsync(team);

Use HTTP headers to control request behavior

You can attach custom headers to a request using the Headers collection. For PowerShell, adding headers is only possible with the Invoke-GraphRequest method. Some Microsoft Graph scenarios use custom headers to adjust the behavior of the request.

// GET https://graph.microsoft.com/v1.0/me/events
var events = await graphClient.Me.Events
    .GetAsync(requestConfig =>
    {
        requestConfig.Headers.Add(
            "Prefer", @"outlook.timezone=""Pacific Standard Time""");
    });

Provide custom query parameters

For SDKs that support the fluent style, you can provide custom query parameter values using the QueryParameters object. For template-based SDKs, the parameters are URL-encoded and added to the request URI. For PowerShell and Go, defined query parameters for a given API are exposed as parameters to the corresponding command.

// GET https://graph.microsoft.com/v1.0/me/calendarView?
// startDateTime=2023-06-14T00:00:00Z&endDateTime=2023-06-15T00:00:00Z
var events = await graphClient.Me.CalendarView
    .GetAsync(requestConfiguration =>
    {
        requestConfiguration.QueryParameters.StartDateTime =
            "2023-06-14T00:00:00Z";
        requestConfiguration.QueryParameters.EndDateTime =
            "2023-06-15T00:00:00Z";
    });