Microsoft Graph を使用すると、より広範な Microsoft 365 エコシステムにアクセスできます。 Microsoft 365 全体のデータを使用してアプリケーションを強化することができます。
Teams SDK を使用すると、アプリケーションが Microsoft.Graph パッケージを介して Microsoft Graph API に簡単にアクセスできるようにします。
Teams SDK を使用すると、アプリケーションが microsoft-teams-graph パッケージを介して Microsoft Graph API に簡単にアクセスできるようにします。
Teams SDK を使用すると、アプリケーションは、 @microsoft/teams.graph、 @microsoft/teams.graph-endpoints 、 @microsoft/teams.graph-endpoints-beta パッケージを介して Microsoft Graph API に簡単にアクセスできます。
パッケージの概要
Graph API サーフェスは広大であり、これはエンドポイント パッケージのサイズに反映されます。 製品のサイズを管理しやすいように、エンドポイント コードがツリーで揺れやすいようにしました。 また、お使いの環境でツリーシェイクがサポートされていない場合に備えて、ほとんどのコードをオプションの依存関係にしました。
| パッケージ | 省略可能 | Contains |
|---|---|---|
@microsoft/teams.graph |
不要 | Graph HTTP リクエストを作成および発行するための小さなクライアント。 |
@microsoft/teams.graph-endpoints |
はい | 実稼働対応の Graph API のいずれかを呼び出す要求ビルダー関数と型。 |
@microsoft/teams.graph-endpoints-beta |
はい | 同じですが、Graph API はまだプレビュー段階です。 |
この SDK を使用して Graph API を呼び出すには、まずお気に入りのパッケージ マネージャーを使用してオプションのエンドポイント パッケージをインストールします。 例:
npm install @microsoft/teams.graph-endpoints
API の呼び出し
Microsoft Graph には、独自のアプリケーション トークンを使用するか、ユーザーのトークンを使用して、アプリケーションからアクセスできます。 アプリケーションにはないリソースにアクセスする必要があるが、ユーザーがアクセスする場合は、ユーザーのスコープ付きグラフ クライアントを使用する必要があります。 アプリケーションがユーザーに代わってリソースにアクセスすることに明示的に同意するには、「 Microsoft Teams でユーザーを認証する」を参照してください。
アプリで Graph を使用してグラフにアクセスするには、 GraphServiceClient オブジェクトを使用して任意のエンドポイントを呼び出します。
アプリで Graph を使用してグラフにアクセスするには、 app.graph オブジェクトを使用して任意のエンドポイントを呼び出します。
using Azure.Identity;
using Microsoft.Graph;
var credential = new ClientSecretCredential(
configuration["AzureAd:TenantId"],
configuration["AzureAd:ClientId"],
configuration["AzureAd:ClientCredentials:0:ClientSecret"]);
var graph = new GraphServiceClient(credential, ["https://graph.microsoft.com/.default"]);
var user = await graph.Me.GetAsync(cancellationToken: cancellationToken);
Console.WriteLine($"User ID: {user?.Id}");
Console.WriteLine($"User Display Name: {user?.DisplayName}");
Console.WriteLine($"User Email: {user?.Mail}");
Console.WriteLine($"User Job Title: {user?.JobTitle}");
# Equivalent of https://learn.microsoft.com/graph/api/user-get
# Gets the details of the bot-user
user = await app.graph.me.get()
print(f"User ID: {user.id}")
print(f"User Display Name: {user.display_name}")
print(f"User Email: {user.mail}")
print(f"User Job Title: {user.job_title}")
ヒント
アクティビティ ハンドラーで app_graph オブジェクトにアクセスすることもできます。 これは app.graph と同等です。
import * as endpoints from '@microsoft/teams.graph-endpoints';
// Equivalent of https://learn.microsoft.com/graph/api/user-get
// Gets the details of the bot-user
app.graph.call(endpoints.me.get).then((user) => {
console.log(`User ID: ${user.id}`);
console.log(`User Display Name: ${user.displayName}`);
console.log(`User Email: ${user.mail}`);
console.log(`User Job Title: ${user.jobTitle}`);
});
ヒント
アクティビティ ハンドラーで appGraph オブジェクトにアクセスすることもできます。 これは app.graph と同等です。
サインインしているユーザーのトークンで Graph にアクセスするには、メッセージ ハンドラーで次の操作を行います。
メッセージ ハンドラー内からユーザーのトークンを使用してグラフにアクセスすることもできます。
using System.Net.Http.Headers;
var flow = teams.GetOAuthFlow("graph");
teams.OnMessage(async (context, cancellationToken) =>
{
var token = await flow.SignInAsync(context, cancellationToken);
if (token is null) return;
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var meJson = await http.GetStringAsync(
"https://graph.microsoft.com/v1.0/me?$select=id,displayName,mail,jobTitle",
cancellationToken);
await context.SendAsync(meJson, cancellationToken);
});
OAuth フローのトークンからクライアントをビルドして、それを所有する接続に常にスコープを設定するようにします。
from microsoft_teams.graph import get_graph_client
graph = app.add_oauth_flow("graph")
@app.on_message
async def handle_message(ctx: ActivityContext[MessageActivity]):
token = await graph.sign_in(ctx)
if token is None:
return # OAuth card sent — resumes on the callback turn
client = get_graph_client(token)
user = await client.me.get()
print(f"User ID: {user.id}")
print(f"User Display Name: {user.display_name}")
print(f"User Email: {user.mail}")
print(f"User Job Title: {user.job_title}")
OAuth フローのトークンからクライアントをビルドして、それを所有する接続に常にスコープを設定するようにします。
import { Client as GraphClient } from '@microsoft/teams.graph';
import * as endpoints from '@microsoft/teams.graph-endpoints';
const graph = app.addOAuthFlow('graph');
// Gets details of the current user
app.on('message', async (ctx) => {
const token = await graph.signIn(ctx);
if (!token) return; // OAuth card sent — resumes on the callback turn
const client = new GraphClient({ token: () => token }, { baseUrlRoot: app.graphBaseUrl });
const me = await client.call(endpoints.me.get);
console.log(`User ID: ${me.id}`);
console.log(`User Display Name: ${me.displayName}`);
console.log(`User Email: ${me.mail}`);
console.log(`User Job Title: ${me.jobTitle}`);
});
Graph クライアント
Graph クライアントは、Microsoft Graph と対話し、特定のユーザーまたはアプリケーションを対象とする要求を発行するためのわかりやすい call 方法を提供します。 Graph エンドポイント パッケージと組み合わせることで、広大な Microsoft Graph API サーフェイスへの検出可能でタイプ セーフなアクセスを提供します。
Graph API のしくみを理解していると、SDK を最大限に活用するのに役立ちます。 たとえば、ユーザーとアプリの間のチャット インスタンスの id を取得するために、 Microsoft Graph は次の方法で公開します。
GET /users/{user-id | user-principal-name}/teamwork/installedApps/{app-installation-id}/chat
グラフ クライアントを使用すると同等のものは次のようになります。
import { users } from '@microsoft/teams.graph-endpoints';
const chat = await client.call(users.teamwork.installedApps.chat.get, {
'user-id': user.id,
'userScopeTeamsAppInstallation-id': appInstallationId,
$select: ['id'],
});
グラフ API は、多くの場合、URL パス、クエリ文字列、または要求本文に入る可能性のある引数を受け入れます。 この例に示すように、すべての引数は graph.call メソッドの 2 番目のパラメーターとして指定されます。 グラフ クライアントは各値をその場所に配置し、要求の作成時に認証トークンを添付して、フェッチ要求を実行します。
グラフ プレビュー API
Graph Preview API は、運用環境での使用は推奨されません。 ただし、プレビュー API を調べる必要がある場合は、 @microsoft/teams.graph-endpoints-beta パッケージを使用すると簡単にできます。
まず、オプションの依存関係をインストールします。
npm install @microsoft/teams.graph-endpoints-beta
次に、通常の @microsoft/teams.graph-endpoints パッケージと同じように使用します。
import * as endpointsBeta from '@microsoft/teams.graph-endpoints-beta';
// Gets the current user details from /beta/me, rather than from /v1.0/me.
const me = await app.graph.call(endpointsBeta.me.get);
@microsoft/teams.graph-endpoints と @microsoft/teams.graph-endpoints-beta の主な違いは、異なる Graph API スキーマを表すことと、graph.call() メソッドが要求を /v1.0 または /beta のいずれかにルーティングすることを認識していることです。 つまり、v1.0 エンドポイントとベータ エンドポイントを組み合わせることが可能であり、たとえば、すべての安定した API についてすでに v1.0 に依存しているコード ベースで新しいベータ API を探索することができます。
カスタム グラフ API の呼び出し
@microsoft/teams.graph-endpoints および @microsoft/teams.graph-endpoints-beta パッケージで提供されるものと同じように機能するカスタム ビルダー関数を作成することができます。 これは、より狭い戻り値の型を提供したい場合、Graph バックエンドでサポートされているがまだエンドポイント パッケージに含まれていない新しい API を呼び出したい場合、またはエンドポイント パッケージへの依存を完全に避けたい場合に便利です。
たとえば、エンドポイント パッケージに依存することなく、displayNameだけを含むように型指定されたオブジェクトをGET https://graph.microsoft.com/beta/me?$select=displayNameして返します。
import { type EndpointRequest } from '@microsoft/teams.graph';
const getMyDisplayName = (): EndpointRequest<{ displayName: string }> => ({
ver: 'beta', // use the beta endpoint; defaults to 'v1.0' if omitted
method: 'get', // HTTP method to use
path: '/me', // endpoint path
paramDefs: {
query: ['$select'], // the $select parameter goes in the query string
},
params: {
$select: ['displayName'], // the attribute(s) to select
},
});
const { displayName } = await app.graph.call(getMyDisplayName);
その他のリソース
Microsoft Graph には、広範かつ徹底的に文書化された API サーフェスが用意されています。 これらの重要なリソースは、あらゆる Graph 開発作業の頼りになるリファレンスとして機能します。
- Microsoft Graph Rest API リファレンス ドキュメントには、アクセス許可要件など、各 API の詳細が記載されています。
- Microsoft Graph REST API ベータ エンドポイント リファレンスには、プレビュー API についての同様の情報が記載されています。
- Graph エクスプローラーを使用すると、API を検出して試乗できます。
さらに、次のエンドポイントは Teams 開発者にとって特に興味深いかもしれません。
| グラフ エンドポイント | 説明 |
|---|---|
| appCatalogs | Teams アプリ カタログ内のアプリ |
| appRoleAssignments | App role assignments |
| applicationTemplates | Microsoft Entra アプリ ギャラリーのアプリケーション |
| アプリケーション | アプリケーション リソース |
| チャット | ユーザー間のチャット リソース |
| communications | 通話とオンライン会議 |
| employeeExperience | 従業員エクスペリエンスとエンゲージメント |
| 私 |
/users と同じですが、スコープは 1 人のユーザー (要求を行っているユーザー) です |
| チーム | Microsoft Teams のチーム リソース |
| teamsTemplates | チームの作成に使用するテンプレート |
| チームワーク | さまざまな Microsoft Teams 機能 |
| users | ユーザー リソース |