添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

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 读取信息

若要从 Microsoft Graph 读取信息,首先需要创建一个请求对象, GET 然后在请求上运行 方法。

TypeScript PowerShell Python
# GET https://graph.microsoft.com/v1.0/users/{user-id}
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
$user = Get-MgUser -UserId $userId
// 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
// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle
import "github.com/microsoftgraph/msgraph-sdk-go/users"
query := users.UserItemRequestBuilderGetQueryParameters{
    Select: []string{"displayName", "jobTitle"},
options := users.UserItemRequestBuilderGetRequestConfiguration{
    QueryParameters: &query,
result, err := client.Me().Get(context.Background(), &options)
# 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"
// GET https://graph.microsoft.com/v1.0/me/calendarview?$select=subject,start,end&$filter=<some condition>&orderBy=start/dateTime&startDateTime=<start>&endDateTime=<end>
import (
    "github.com/microsoftgraph/msgraph-sdk-go/users"
    "context"
startDateTime := "2021-11-18T00:00:00"
endDateTime := "2021-11-19T00:00:00"
filter := "<filter condition>"
query := users.ItemCalendarViewRequestBuilderGetQueryParameters{
    Filter:  &filter,
    Orderby: []string{"start/dateTime"},
    Select: []string{
        "subject",
        "start",
        "end",
    StartDateTime: &startDateTime,
    EndDateTime:   &endDateTime,
options := users.ItemCalendarViewRequestBuilderGetRequestConfiguration{
    QueryParameters: &query,
result, err := client.Me().CalendarView().Get(context.Background(), &options)
# 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))
// 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
// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
messageId := "AQMkAGUy.."
result, err = client.Me().Messages().ByMessageId(messageId).Get(context.Background(), nil)
# GET https://graph.microsoft.com/v1.0/me/messages/{message-id}
message = asyncio.run(client.me
                      .messages('messageId')
                      .get())

在请求main实体的同时,可以使用$expand筛选器请求相关实体或实体集合。

TypeScript PowerShell Python
// 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.Expand = 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
// GET https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages/{message-id}?$expand=attachments
import (
    "github.com/microsoftgraph/msgraph-sdk-go/users"
    "context"
mailFolderId := "inbox"
messageId := "AQMkAGUy..."
expand := users.ItemMailFoldersItemMessagesMessageItemRequestBuilderGetQueryParameters{
    Expand: []string{"attachments"},
options := users.ItemMailFoldersItemMessagesMessageItemRequestBuilderGetRequestConfiguration{
    QueryParameters: &expand,
result, err := client.
    Me().
    MailFolders().
    ByMailFolderId(mailFolderId).
    Messages().
    ByMessageId(messageId).
    Get(context.Background(), &options)
# 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

TypeScript PowerShell Python
// 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
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
messageId := "AQMkAGUy..."
err := client.Me().Messages().ByMessageId(messageId).Delete(context.Background(), 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);
# POST https://graph.microsoft.com/v1.0/users/{user-id}/calendars
$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"
New-MgUserCalendar -UserId $userId -Name "Volunteer"
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)
const teamId = '71766077-aacc-470a-be5e-ba47db3b2e88';
let res = await client.api(`/teams/${teamId}`)
  .update(teamSettings);
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" }
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.Teams().ByTeamId(teamId).Patch(context.Background(), &options)
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))

使用 HTTP 标头控制请求行为

可以使用 Header() 函数将自定义标头附加到请求。 对于 PowerShell,只能通过 Invoke-GraphRequest 方法添加标头。 许多 Microsoft Graph 方案使用自定义标头来调整请求的行为。

TypeScript PowerShell Python
//  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""" }
import (
    abstractions "github.com/microsoft/kiota-abstractions-go"
    "github.com/microsoftgraph/msgraph-sdk-go/users"
    "context"
headers := abstractions.NewRequestHeaders()
headers.Add("Prefer", "outlook.timezone=\"Pacific Standard Time\"")
options := users.ItemEventsRequestBuilderGetRequestConfiguration{
    Headers: headers,
result, err := client.Me().Events().Get(context.Background(), &options)
# 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 的已定义查询参数将作为参数公开给相应的命令。

TypeScript PowerShell Python
//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"
endDateTime := "2021-11-19T00:00:00"
query := users.ItemCalendarViewRequestBuilderGetQueryParameters{
    StartDateTime: &startDateTime,
    EndDateTime:   &endDateTime,
options := users.ItemCalendarViewRequestBuilderGetRequestConfiguration{
    QueryParameters: &query,
result, err := client.Me().CalendarView().Get(context.Background(), &options)
# 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))