大网数据广告活动
Microsoft Graph 接口

使用 Microsoft Graph SDK 进行 API 调用

· 52CE 我爱测

提供有关使用 SDK 创建 Microsoft Graph HTTP 请求的说明。

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

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

C#

// GET https://graph.microsoft.com/v1.0/me

var user = await graphClient.Me
    .Request()
    .GetAsync();

TypeScript

// GET https://graph.microsoft.com/v1.0/me

let user = await client.api('/me').get();

Java

// GET https://graph.microsoft.com/v1.0/me

final User user = graphClient.me()
    .buildRequest()
    .get();

PowerShell

# GET https://graph.microsoft.com/v1.0/users/{user-id}

$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"

$user = Get-MgUser -UserId $userId

Go

Important: Microsoft Graph SDK for Go 目前处于预览状态。 不支持在生产环境中使用此 SDK。

// GET https://graph.microsoft.com/v1.0/me

result, err := client.Me().Get(nil)

使用$select控制返回的属性

检索实体时,并非所有属性都会自动检索;有时需要显式选择它们。 此外,在某些情况下,不需要返回默认属性集。 仅选择所需的属性可以提高请求的性能。 可以自定义请求,以包含 $select 包含属性列表的查询参数。

C#

// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle

var user = await graphClient.Me
    .Request()
    .Select(u => new {
        u.DisplayName,
        u.JobTitle
    })
    .GetAsync();

TypeScript

// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle

let user = await client.api('/me')
  .select('displayName', 'jobTitle')
  .get();

Java

// GET https://graph.microsoft.com/v1.0/me?$select=displayName,jobTitle

final User user = graphClient.me()
    .buildRequest()
    .select("DisplayName,JobTitle")
    .get();

PowerShell

# 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

Go

Important: 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{
    Q: &query,
}

result, err := client.Me().Get(&options)

检索实体列表

检索实体列表类似于检索单个实体,但用于配置请求的其他许多选项除外。 查询 $filter 参数可用于将结果集减少到仅与提供的条件匹配的行。 查询 $orderBy 参数将请求服务器提供按指定属性排序的实体列表。

Note: 对资源Azure Active Directory请求需要使用高级查询功能。 如果您收到指示错误请求、不支持的 $count 查询或包含意外结果的响应(包括查询 ConsistencyLevel 参数和标头)的响应,则可能会允许请求成功。 有关详细信息和示例,请参阅目录对象Azure AD功能。

C#

// GET https://graph.microsoft.com/v1.0/me/messages?$select=subject,sender&$filter=<some condition>&orderBy=receivedDateTime

var messages = await graphClient.Me.Messages
    .Request()
    .Select(m => new {
        m.Subject,
        m.Sender
    })
    .Filter("<filter condition>")
    .OrderBy("receivedDateTime")
    .GetAsync();

TypeScript

// 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();

Java

// 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();

PowerShell

# 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"

Go

Important: 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"
)

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_escaped: []string{
        "subject",
        "start",
        "end",
    },
    StartDateTime: &startDateTime,
    EndDateTime:   &endDateTime,
}

options := cv.CalendarViewRequestBuilderGetOptions{
    Q: &query,
}

result, err := client.Me().CalendarView().Get(&options)

检索实体列表时返回的对象可能是分页集合。 有关如何获取实体完整列表的详细信息,请参阅 通过集合进行分页。

访问集合的项

对于支持流式样式的 SDK,可以使用数组索引访问实体集合。 对于基于模板的 SDK,足以在集合后的路径段中嵌入项标识符。 对于 PowerShell,标识符作为参数传递。

C#

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}

string messageId = "AQMkAGUy..";
var message = await graphClient.Me.Messages[messageId]
    .Request()
    .GetAsync();

TypeScript

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}

let messageId = 'AQMkAGUy..';
let messages = await client.api(`/me/messages/${messageId}`)
  .get();

Java

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}

final String messageId = "AQMkAGUy..";
final Message message = graphClient.me().messages(messageId)
    .buildRequest()
    .get();

PowerShell

# 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

Go

Important: 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(nil)

使用$expand访问相关实体

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

C#

// GET https://graph.microsoft.com/v1.0/me/messages/{message-id}?$expand=attachments

string messageId = "AQMkAGUy...";
var message = await graphClient.Me.Messages[messageId]
    .Request()
    .Expand("attachments")
    .GetAsync();

TypeScript

// 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();

Java

// 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();

PowerShell

# 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

Go

Important: 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"
)

mailFolderId := "inbox"
messageId := "AQMkAGUy..."

expand := item.MessageRequestBuilderGetQueryParameters{
    Expand: []string{"attachments"},
}

options := item.MessageRequestBuilderGetOptions{
    Q: &expand,
}

result, err := client
    .Me()
    .MailFoldersById(mailFolderId)
    .MessagesById(messageId)
    .Get(&options)

删除实体

删除请求的构造方式与检索实体的请求相同,但使用 DELETE 请求而不是 GET请求。

C#

// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}

string messageId = "AQMkAGUy...";
var message = await graphClient.Me.Messages[messageId]
    .Request()
    .DeleteAsync();

TypeScript

// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}

let messageId = 'AQMkAGUy..';
let message = await client.api('/me/messages/${messageId}')
  .delete();

Java

// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}

final String messageId = "AQMkAGUy...";
final Message message = graphClient.me().messages(messageId)
    .buildRequest()
    .delete();

PowerShell

# 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

Go

Important: 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(nil)

发出 POST 请求以创建新实体

对于支持流式样式的 SDK,可以使用 Add 方法将新项添加到集合中。 对于基于模板的 SDK,请求对象会公开一种方法 post 。 对于 PowerShell,可以使用一个 New-* 命令来接受映射到要添加的实体的参数。 创建的实体通常从调用返回。

C#

// POST https://graph.microsoft.com/v1.0/me/calendars

var calendar = new Calendar
{
    Name = "Volunteer"
};

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

TypeScript

//POST https://graph.microsoft.com/v1.0/me/calendars

const calendar = {
  name: 'Volunteer'
};

let newCalendar = await client.api('/me/calendars')
  .post(calendar);

Java

// 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);

PowerShell

# POST https://graph.microsoft.com/v1.0/users/{user-id}/calendars

$userId = "71766077-aacc-470a-be5e-ba47db3b2e88"

New-MgUserCalendar -UserId $userId -Name "Volunteer"

Go

Important: 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"
)

calendar := graph.NewCalendar()
name := "Volunteer"
calendar.SetName(&name)

options := calendars.CalendarsRequestBuilderPostOptions{
    Body: calendar,
}

result, err := client.Me().Calendars().Post(&options)

使用 PATCH 更新现有实体

Microsoft Graph中的大多数更新都是使用方法PATCH执行的,因此只需在传递的对象中包含要更改的属性。

C#

// 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]
    .Request()
    .UpdateAsync(team);

TypeScript

//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);

Java

// 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);

PowerShell

# 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" }

Go

Important: 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"
)

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(&options)

使用 HTTP 标头控制请求行为

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

C#

//  GET https://graph.microsoft.com/v1.0/users/{user-id}/events

var events = await graphClient.Me.Events
    .Request()
    .Header("Prefer",@"outlook.timezone=""Pacific Standard Time""")
    .Select( e => new {
        e.Subject,
        e.Body,
        e.BodyPreview
    })
    .GetAsync();

TypeScript

// 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();

Java

//  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();

PowerShell

# 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""" }

Go

Important: 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"
)

options := events.EventsRequestBuilderGetOptions{
    H: map[string]string{
        "Prefer": "outlook.timezone=\"Pacific Standard Time\"",
    },
}

result, err := client.Me().Events().Get(&options)

提供自定义查询参数

对于支持流式样式的 SDK,可以使用对象列表 QueryOptions 提供自定义查询参数值。 对于基于模板的 SDK,参数是 URL 编码的,并添加到请求 URI 中。 对于 PowerShell 和 Go,给定 API 的定义查询参数将作为参数公开给相应的命令。

C#

//GET https://graph.microsoft.com/v1.0/me/calendarView

var queryOptions = new List<QueryOption>()
{
    new QueryOption("startdate", "2020-12-01T00:00:00Z"),
    new QueryOption("enddate", "2020-12-30T00:00:00Z")
};

var calendar = await graphClient.Me.CalendarView()
    .Request(queryOptions)
    .GetAsync();

TypeScript

// 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();

Java

//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();

PowerShell

# 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"

Go

Important: 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"
)

startDateTime := "2021-11-18T00:00:00"
endDateTime := "2021-11-19T00:00:00"

query := cv.CalendarViewRequestBuilderGetQueryParameters{
    StartDateTime: &startDateTime,
    EndDateTime:   &endDateTime,
}

options := cv.CalendarViewRequestBuilderGetOptions{
    Q: &query,
}

result, err := client.Me().CalendarView().Get(&options)

历史资料。此文对应 2023-02-03 的中文文档快照,适用产品版本和命令行为以原文为准。

来源与署名:Microsoft 和文档贡献者(原始作者元数据 DarrelMiller)。固定版本原文。文档采用 CC BY 4.0,示例代码采用 MIT 授权。本站将 Markdown 转为 HTML,规范化链接,移除外部媒体和导航标记。

资料来源与适用范围

资料来源
Microsoft / Microsoft Graph 中文文档历史快照
适用范围
历史中文快照 2023-02-03;详见原文产品版本;文档日期 未标明
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-16
授权说明
CC BY 4.0(文档)/ MIT(示例代码)

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。