使用 Microsoft Graph SDK 进行 API 调用
本文内容
Microsoft Graph SDK 服务库提供了一个客户端类,你可以将其用作创建所有 API 请求的起点。 客户端类有两种样式:一种使用 fluent 接口创建请求 (例如, client.Users["user-id"].Manager
) ,另一种使用路径字符串 (例如 api("/users/user-id/manager")
) 。 当具有请求对象时,可以指定各种选项(例如筛选和排序),最后,选择要执行的操作类型。
还有 Microsoft Graph PowerShell SDK ,它根本没有客户端类。 相反,所有请求都表示为 PowerShell 命令。 例如,若要获取用户的经理,命令为 Get-MgUserManager
。 有关查找 API 调用的命令的详细信息,请参阅 导航 Microsoft Graph PowerShell SDK 。
若要从 Microsoft Graph 读取信息,首先需要创建一个请求对象, GET
然后在请求上运行 方法。
// GET https://graph.microsoft.com/v1.0/me
var user = await graphClient.Me
.GetAsync();
// GET https://graph.microsoft.com/v1.0/me
let user = await client.api('/me').get();
// GET https://graph.microsoft.com/v1.0/me
final User user = graphClient.me()
.buildRequest()
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$user = Get-MgUser -UserId $userId
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me
result, err := client.Me().Get(context.Background(), nil)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/me
user = asyncio.run(client.me.get())
使用$select控制返回的属性
检索实体时,并非所有属性都会自动检索;有时需要显式选择它们。 此外,在某些情况下,无需返回默认属性集。 仅选择所需的属性可以提高请求的性能。 可以自定义请求,以包含 $select
具有属性列表的查询参数。
// 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
let user = await client.api('/me')
.select('displayName', 'jobTitle')
.get();
// 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
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
import me "github.com/microsoftgraph/msgraph-sdk-go/me"
query := me.MeRequestBuilderGetQueryParameters{
Select_escaped: []string{"displayName", "jobTitle"},
}
options := me.MeRequestBuilderGetOptions{
QueryParameters: &query,
}
result, err := client.Me().Get(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
query_params = MeRequestBuilder.MeRequestBuilderGetQueryParameters(
select=['displayName', 'jobTitle']
)
request_config = MeRequestBuilder.MeRequestBuilderGetRequestConfiguration(
query_parameters=query_params,
)
user = asyncio.run(client.me
.get(request_configuration=request_config))
检索实体列表
检索实体列表类似于检索单个实体,只不过还有其他许多用于配置请求的选项。 查询 $filter
参数可用于将结果集减少到仅那些与所提供的条件匹配的行。 查询 $orderBy
参数将请求服务器提供按指定属性排序的实体列表。
注意
某些 Azure Active Directory 资源请求需要使用高级查询功能。 如果收到指示错误请求、不支持的查询或包含意外结果的响应(包括 $count
查询参数和 ConsistencyLevel
标头)的响应,则请求可能会成功。 有关详细信息和示例,请参阅 Azure AD 目录对象上的高级查询功能 。
// GET https://graph.microsoft.com/v1.0/me/messages?$select=subject,sender&$filter=<some condition>&orderBy=receivedDateTime
var messages = await graphClient.Me.Messages
.GetAsync( requestConfig =>
{
requestConfig.QueryParameters.Select = new string[] { "subject", "sender"};
requestConfig.QueryParameters.Filter = "<filter condition>";
requestConfig.QueryParameters.Orderby = new string[] { "receivedDateTime" };
});
// GET https://graph.microsoft.com/v1.0/me/messages?$select=subject,sender
// &$filter=<some condition>&orderBy=receivedDateTime
let messages = await client.api('/me/messages')
.select('subject', 'sender')
.filter('some condition')
.orderBy('receivedDateTime')
.get();
// GET https://graph.microsoft.com/v1.0/me/messages?$select=subject,sender&$filter=<some condition>&orderBy=receivedDateTime
final IMessageCollectionPage messages = graphClient.me().messages()
.buildRequest()
.select("Subject,Sender")
.filter("<filter condition>")
.orderBy("receivedDateTime")
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}/messages?$select=subject,sender&
# $filter=<some condition>&orderBy=receivedDateTime
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
# -Sort is equivalent to $orderby
# -Filter is equivalent to $filter
$messages = Get-MgUserMessage -UserId $userId -Property Subject,Sender `
-Sort ReceivedDateTime -Filter "some condition"
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me/calendarview?$select=subject,start,end&$filter=<some condition>&orderBy=start/dateTime&startDateTime=<start>&endDateTime=<end>
import (
cv "github.com/microsoftgraph/msgraph-sdk-go/me/calendarview"
"context"
)
startDateTime := "2021-11-18T00:00:00"
endDateTime := "2021-11-19T00:00:00"
filter := "<filter condition>"
query := cv.CalendarViewRequestBuilderGetQueryParameters{
Filter: &filter,
Orderby: []string{"start/dateTime"},
Select: []string{
"subject",
"start",
"end",
},
StartDateTime: &startDateTime,
EndDateTime: &endDateTime,
}
options := cv.CalendarViewRequestBuilderGetOptions{
QueryParameters: &query,
}
result, err := client.Me().CalendarView().Get(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/me/messages?$select=sender,subject&$filter=<some condition>&orderBy=receivedDateTime
query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
select=['sender', 'subject'],
filter='<filter condition>',
orderby=['receivedDateTime']
)
request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration(
query_parameters= query_params
)
messages = asyncio.run(client.me
.messages
.get(request_configuration=request_config))
检索实体列表时返回的对象可能是分页集合。 有关如何获取实体的完整列表的详细信息,请参阅 对集合进行分页 。
访问集合的项
对于支持流畅样式的 SDK,可以使用数组索引访问实体集合。 对于基于模板的 SDK,将项标识符嵌入集合后面的路径段中就足够了。 对于 PowerShell,标识符作为参数传递。
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
string messageId = "AQMkAGUy..";
var message = await graphClient.Me.Messages[messageId]
.GetAsync();
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
let messageId = 'AQMkAGUy..';
let messages = await client.api(`/me/messages/${messageId}`)
.get();
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
final String messageId = "AQMkAGUy..";
final Message message = graphClient.me().messages(messageId)
.buildRequest()
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}/messages/{message-id}
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$messageId = "AQMkAGUy.."
$message = Get-MgUserMessage -UserId $userId -MessageId $messageId
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
messageId := "AQMkAGUy.."
result, err = client.Me().MessagesById(messageId).Get(context.Background(), nil)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
message = asyncio.run(client.me
.messages('messageId')
.get())
在请求主实体的同时,可以使用 $expand
筛选器请求相关实体或实体集合。
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
string messageId = "AQMkAGUy...";
var message = await graphClient.Me.Messages[messageId]
.GetAsync( requestConfig => requestConfig.QueryParameters.Select = new string[] { "attachments" });
// GET https://graph.microsoft.com/v1.0/me/messages?$expand=attachments
let messageId = 'AQMkAGUy..';
let message = await client.api(`/me/messages/${messageId}`)
.expand('attachments')
.get();
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
final String messageId = "AQMkAGUy...";
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
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages/{message-id}?$expand=attachments
import (
events "github.com/microsoftgraph/msgraph-sdk-go/me/mailfolders/item/messages/item"
"context"
)
mailFolderId := "inbox"
messageId := "AQMkAGUy..."
expand := item.MessageRequestBuilderGetQueryParameters{
Expand: []string{"attachments"},
}
options := item.MessageRequestBuilderGetOptions{
QueryParameters: &expand,
}
result, err := client
.Me()
.MailFoldersById(mailFolderId)
.MessagesById(messageId)
.Get(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments
query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
expand=['attachments',]
)
request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration(
query_parameters=query_params,
)
messages = asyncio.run(client.me
.messages_by_id('msgId')
.get(request_configuration=request_config))
删除实体
删除请求的构造方式与检索实体的请求相同,但使用 DELETE
请求而不是 GET
。
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
string messageId = "AQMkAGUy...";
await graphClient.Me.Messages[messageId]
.DeleteAsync();
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
let messageId = 'AQMkAGUy..';
let message = await client.api('/me/messages/${messageId}')
.delete();
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
final String messageId = "AQMkAGUy...";
final Message message = graphClient.me().messages(messageId)
.buildRequest()
.delete();
# DELETE https://graph.microsoft.com/v1.0/users/{user-id}/messages/{message-id}
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$messageId = "AQMkAGUy.."
Remove-MgUserMessage -UserId $userId -MessageId $messageId
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
messageId := "AQMkAGUy..."
err := client.Me().MessagesById(messageId).Delete(context.Background(), nil)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
asyncio.run(client.me.messages_by_id('msgId').delete())
发出 POST 请求以创建新实体
对于支持流畅样式的 SDK,可以使用 方法将新项添加到集合 Add
中。 对于基于模板的 SDK,请求对象公开方法 post
。 对于 PowerShell,可以使用一个 New-*
命令来接受映射到要添加的实体的参数。 创建的实体通常从调用返回。
// 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
const calendar = {
name: 'Volunteer'
};
let newCalendar = await client.api('/me/calendars')
.post(calendar);
// 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);
# POST https://graph.microsoft.com/v1.0/users/{user-id}/calendars
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
New-MgUserCalendar -UserId $userId -Name "Volunteer"
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// POST https://graph.microsoft.com/v1.0/me/calendars
import (
calendars "github.com/microsoftgraph/msgraph-sdk-go/me/calendars"
graph "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
"context"
)
calendar := graph.NewCalendar()
name := "Volunteer"
calendar.SetName(&name)
options := calendars.CalendarsRequestBuilderPostOptions{
Body: calendar,
}
result, err := client.Me().Calendars().Post(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# POST https://graph.microsoft.com/v1.0/me/calendars
calendar = Calendar()
calendar.name = "Volunteer"
new_calendar = asyncio.run(client.me.calendars.post(calendar))
使用 PATCH 更新现有实体
Microsoft Graph 中的大多数更新都是使用 PATCH
方法执行的,因此只需在传递的对象中包含要更改的属性。
// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
var team = new Team
{
FunSettings = new TeamFunSettings
{
AllowGiphy = true,
GiphyContentRating = GiphyRatingType.Strict
}
};
var teamId = "71766077-aacc-470a-be5e-ba47db3b2e88";
await graphClient.Teams[teamId]
.PatchAsync(team);
//PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
const teamSettings = {
funSettings: {
allowGiphy: true,
giphyContentRating: 'strict'
}
};
const teamId = '71766077-aacc-470a-be5e-ba47db3b2e88';
let res = await client.api(`/teams/${teamId}`)
.update(teamSettings);
// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
final Team team = new Team();
team.FunSettings = new TeamFunSettings();
team.FunSettings.AllowGiphy = true;
team.FunSettings.GiphyContentRating = GiphyRatingType.STRICT;
final String teamId = "71766077-aacc-470a-be5e-ba47db3b2e88";
graphClient.teams(teamId)
.buildRequest()
.patch(team);
# PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
$teamId = "71766077-aacc-470a-be5e-ba47db3b2e88"
Update-MgTeam -TeamId $teamId -FunSettings @{ AllowGiphy = $true; GiphyContentRating = "strict" }
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
import (
graph "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
teams "github.com/microsoftgraph/msgraph-sdk-go/teams/item"
"context"
)
teamId := "71766077-aacc-470a-be5e-ba47db3b2e88"
funSettings := graph.NewTeamFunSettings()
allowGiphy := true
funSettings.SetAllowGiphy(&allowGiphy)
giphyRating := graph.STRICT_GIPHYRATINGTYPE
funSettings.SetGiphyContentRating(&giphyRating)
team := graph.NewTeam()
team.SetFunSettings(funSettings)
options := teams.TeamRequestBuilderPatchOptions{
Body: team,
}
client.TeamsById(teamId).Patch(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# PATCH https://graph.microsoft.com/v1.0/teams/{team-id}
team = Team()
fun_settings = TeamFunSettings()
fun_settings.allow_giphy = True
fun_settings.giphy_content_rating = GiphyRatingType.Strict
team.fun_settings = fun_settings
asyncio.run(client.teams_by_id('teamId').patch(team))
可以使用 Header()
函数将自定义标头附加到请求。 对于 PowerShell,只能通过 Invoke-GraphRequest
方法添加标头。 许多 Microsoft Graph 方案使用自定义标头来调整请求的行为。
// GET https://graph.microsoft.com/v1.0/users/{user-id}/events
var events = await graphClient.Me.Events
.GetAsync( requestConfig =>
{
requestConfig.Headers.Add("Prefer", @"outlook.timezone=""Pacific Standard Time""");
requestConfig.QueryParameters.Select = new string[] {"subject", "body", "bodyPreview"};
});
// GET https://graph.microsoft.com/v1.0/me/events
let events = await client.api('/me/events')
.header('Prefer','outlook.timezone="Pacific Standard Time"')
.select('subject,body,bodyPreview,organizer,attendees,start,end,location')
.get();
// GET https://graph.microsoft.com/v1.0/users/{user-id}/events
final Event events = graphClient.me().events()
.buildRequest(new HeaderOption("Prefer","outlook.timezone=\"Pacific Standard Time\""))
.select("Subject,Body,BodyPreview")
.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""" }
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
// GET https://graph.microsoft.com/v1.0/me/events
import (
events "github.com/microsoftgraph/msgraph-sdk-go/me/events"
"context"
)
options := events.EventsRequestBuilderGetOptions{
H: map[string]string{
"Prefer": "outlook.timezone=\"Pacific Standard Time\"",
},
}
result, err := client.Me().Events().Get(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
# GET https://graph.microsoft.com/v1.0/users/{user-id}/events
request_config = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration(
headers={'Prefer': 'outlook.timezone="Pacific Standard Time"'},
)
events = asyncio.run(client.me
.events
.get(request_configuration=request_config))
提供自定义查询参数
对于支持流畅样式的 SDK,可以使用对象列表 QueryOptions
提供自定义查询参数值。 对于基于模板的 SDK,参数经过 URL 编码并添加到请求 URI。 对于 PowerShell 和 Go,给定 API 的已定义查询参数将作为参数公开给相应的命令。
//GET https://graph.microsoft.com/v1.0/me/calendarView
var calendar = await graphClient.Me.CalendarView
.GetAsync(requestConfiguration =>
{
requestConfiguration.QueryParameters.StartDateTime = "2020-12-01T00:00:00Z";
requestConfiguration.QueryParameters.EndDateTime = "2020-12-30T00:00:00Z";
});
// GET https://graph.microsoft.com/v1.0/me/calendar/calendarView
const start = '2020-01-01T19:00:00';
const end = '2020-01-07T19:00:00';
let calendar = await client
.api(`/me/calendar/calendarView?startDateTime=${start}&endDateTime=${end}`)
.get();
//GET https://graph.microsoft.com/v1.0/me/calendarView
final IEventCollectionPage calendar = graphClient.me().calendarView()
.buildRequest(new QueryOption("startdate", "2020-12-01T00:00:00Z"),
new QueryOption("enddate", "2020-12-30T00:00:00Z"))
.get();
# GET https://graph.microsoft.com/v1.0/users/{user-id}/calendars/{calendar-id}/calendarView
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$calendarId = "AQMkAGUy..."
$events = Get-MgUserCalendarView -UserId $userId -CalendarId $calendarId `
-StartDateTime "2020-08-31T00:00:00Z" -EndDateTime "2020-09-02T00:00:00Z"
重要
Microsoft Graph SDK for Go 目前为预览版。 不支持在生产环境中使用此 SDK。
//GET https://graph.microsoft.com/v1.0/me/calendarView
import (
cv "github.com/microsoftgraph/msgraph-sdk-go/me/calendarview"
"context"
)
startDateTime := "2021-11-18T00:00:00"
endDateTime := "2021-11-19T00:00:00"
query := cv.CalendarViewRequestBuilderGetQueryParameters{
StartDateTime: &startDateTime,
EndDateTime: &endDateTime,
}
options := cv.CalendarViewRequestBuilderGetOptions{
QueryParameters: &query,
}
result, err := client.Me().CalendarView().Get(context.Background(), &options)
重要
适用于 Python 的 Microsoft Graph SDK 目前为预览版。 不支持在生产环境中使用此 SDK。
Todo
# GET https://graph.microsoft.com/v1.0/me/calendarView
query_params = CalendarViewRequestBuilder.CalendarViewRequestBuilderGetQueryParameters(
start_date_time='2020-12-01T00:00:00Z',
end_date_time='2020-12-30T00:00:00Z',
)
request_config = CalendarViewRequestBuilder.CalendarViewRequestBuilderGetRequestConfiguration(
query_parameters=query_params,
)
calendar = asyncio.run(client.me
.calendar_view
.get(request_configuration=request_config))