The Microsoft Graph SDK service libraries provide a client class that you can 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 a variety of options such as filtering and sorting, and finally, you select the type of operation you want to perform.
There is also the Microsoft Graph PowerShell SDK, which has no client class at all. 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.
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# GET https://graph.microsoft.com/v1.0/me
user = await graph_client.me.get()
// GET https://graph.microsoft.com/v1.0/me
const user = await graphClient.api('/me').get();
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, in some scenarios it isn't necessary to return the default set of properties. 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 =
new string[] { "displayName", "jobTitle" };
});
// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
final User user = graphClient.me().buildRequest().select("displayName,jobTitle")
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}?$select=displayName,jobTitle
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
# The -Property parameter causes a $select parameter to be included in the request
$user = Get-MgUser -UserId $userId -Property DisplayName,JobTitle
Important
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
# msgraph.generated.users.item.user_item_request_builder
query_params = UserItemRequestBuilder.UserItemRequestBuilderGetQueryParameters(
select=['displayName', 'jobTitle']
)
config = UserItemRequestBuilder.UserItemRequestBuilderGetRequestConfiguration(
query_parameters=query_params
)
user = await graph_client.me.get(config)
// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
const user = await graphClient
.api('/me')
.select(['displayName', 'jobTitle'])
.get();
Retrieve a list of entities
Retrieving a list of entities is similar to retrieving a single entity except there a number of other options for configuring the request. The $filter query parameter can be used to reduce the result set to only those rows that match the provided condition. The $orderby query parameter will request that the server provide the list of entities sorted by the specified properties.
Note
Some requests for Azure Active Directory 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.
The object returned when retrieving a list of entities is likely to 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 is 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();
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
result, _ := graphClient.Me().Messages().
ByMessageId(messageId).Get(context.Background(), nil)
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
final Message message = graphClient.me().messages(messageId).buildRequest().get();
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
# message_id is a string containing the id property of the message
message = await graph_client.me.messages.by_message_id(message_id).get()
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
const message = await graphClient.api(`/me/messages/${messageId}`).get();
Use $expand to access related entities
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 = new string[] { "attachments" });
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
// import github.com/microsoftgraph/msgraph-sdk-go/users
expand := users.ItemMessagesMessageItemRequestBuilderGetQueryParameters{
Expand: []string{"attachments"},
}
options := users.ItemMessagesMessageItemRequestBuilderGetRequestConfiguration{
QueryParameters: &expand,
}
// messageId is a string containing the id property of the message
result, _ := graphClient.Me().Messages().
ByMessageId(messageId).Get(context.Background(), &options)
// GET
// https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
// messageId is a string containing the id property of the message
final Message message = graphClient.me().messages(messageId).buildRequest()
.expand("attachments").get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}/messages?$expand=attachments
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$messageId = "AQMkAGUy.."
# -ExpandProperty is equivalent to $expand
$message = Get-MgUserMessage -UserId $userId -MessageId $messageId -ExpandProperty Attachments
Important
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
# message_id is a string containing the id property of the message
# msgraph.generated.users.item.messages.item.message_item_request_builder
query_params = MessageItemRequestBuilder.MessageItemRequestBuilderGetQueryParameters(
expand=['attachments']
)
config = MessageItemRequestBuilder.MessageItemRequestBuilderGetRequestConfiguration(
query_parameters=query_params
)
message = await graph_client.me.messages.by_message_id(message_id).get(config)
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
// messageId is a string containing the id property of the message
const message = await graphClient
.api(`/me/messages/${messageId}`)
.expand('attachments')
.get();
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();
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
err := graphClient.Me().Messages().
ByMessageId(messageId).Delete(context.Background(), nil)
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
graphClient.me().messages(messageId).buildRequest().delete();
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
# message_id is a string containing the id property of the message
await graph_client.me.messages.by_message_id(message_id).delete()
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
// messageId is a string containing the id property of the message
await graphClient.api(`/me/messages/${messageId}`).delete();
Make a POST request to create a new entity
For SDKs that support a fluent style, new items can be added to collections with an Add method. For template-based SDKs, the request object exposes a post method. For PowerShell, a New-* command is available that accepts parameters that map to the entity to add. The created entity is usually 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);
// POST https://graph.microsoft.com/v1.0/me/calendars
calendar := models.NewCalendar()
name := "Volunteer"
calendar.SetName(&name)
result, _ := graphClient.Me().Calendars().Post(context.Background(), calendar, nil)
// POST https://graph.microsoft.com/v1.0/me/calendars
final Calendar calendar = new Calendar();
calendar.name = "Volunteer";
final Calendar newCalendar = graphClient.me().calendars().buildRequest()
.post(calendar);
Most updates in Microsoft Graph are performed using a PATCH method and therefore it is only necessary to include the properties that 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);
// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
final Team team = new Team();
final TeamFunSettings funSettings = new TeamFunSettings();
funSettings.allowGiphy = true;
funSettings.giphyContentRating = GiphyRatingType.STRICT;
team.funSettings = funSettings;
// teamId is a string containing the id property of the team
graphClient.teams(teamId).buildRequest().patch(team);
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
# msgraph.generated.models.team_fun_settings.TeamFunSettings
fun_settings = TeamFunSettings()
fun_settings.allow_giphy = True
# msgraph.generated.models.giphy_rating_type
fun_settings.giphy_content_rating = GiphyRatingType.Strict
# msgraph.generated.models.team.Team
team = Team()
team.fun_settings = fun_settings
# team_id is a string containing the id property of the team
await graph_client.teams.by_team_id(team_id).patch(team)
// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
const team: Team = {
funSettings: {
allowGiphy: true,
giphyContentRating: 'strict',
},
};
// teamId is a string containing the id property of the team
await graphClient.api(`/teams/${teamId}`).update(team);
Use HTTP headers to control request behavior
You can use a Header() function to attach custom headers to a request. For PowerShell, adding headers is only possible with the Invoke-GraphRequest method. A number of Microsoft Graph scenarios use custom headers to adjust the behavior of the request.
// GET https://graph.microsoft.com/v1.0/me/events
final EventCollectionPage events = graphClient.me().events()
.buildRequest(
new HeaderOption("Prefer", "outlook.timezone=\"Pacific Standard Time\""))
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}/events
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$requestUri = "/v1.0/users/" + $userId + "/events"
$events = Invoke-GraphRequest -Method GET -Uri $requestUri `
-Headers @{ Prefer = "outlook.timezone=""Pacific Standard Time""" }
Important
The Microsoft Graph SDK for Python is currently in preview. Use of this SDK in production is not supported.
# GET https://graph.microsoft.com/v1.0/me/events
# msgraph.generated.users.item.events.events_request_builder
config = EventsRequestBuilder.EventsRequestBuilderGetRequestConfiguration(
headers={ 'Prefer': 'outlook.timezone="Pacific Standard Time"' }
)
events = await graph_client.me.events.get(config)
// GET https://graph.microsoft.com/v1.0/me/events
const events = await graphClient
.api('/me/events')
.header('Prefer', 'outlook.timezone="Pacific Standard Time"')
.get();
Provide custom query parameters
For SDKs that support a fluent style, you can provide custom query parameter values by using a list of QueryOptions objects. 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
final EventCollectionPage events = graphClient.me().events()
.buildRequest(
new QueryOption("startDateTime", "2023-06-14T00:00:00Z"),
new QueryOption("endDateTime", "2023-06-15T00:00:00Z")
).get();