Generated banner for Msgraph SDK
Generated logo for Msgraph SDK

Msgraph SDK

GitHubOfficialFirst committed by lovyjainDistributed by GitHub

  • Skill
  • Tool integration
  • Automation and integrations
  • MIT
  • Low risk

From the author

Integrate Microsoft Graph SDK into any project — .NET, TypeScript/JavaScript, or Python. Covers auth patterns (client credentials, OBO, managed identity), SDK setup, calling Graph APIs, batching, delta queries, change notifications, throttling, and permission scopes. Use when accessing Microsoft 365 data (users, mail, calendar, Teams, files, SharePoint) from any application type.
— the description by lovyjain

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Microsoft Graph SDK skill provides a structured approach to integrating Microsoft 365 services into custom applications. It covers essential implementation details including authentication patterns, SDK initialization, fluent API usage, and advanced data handling techniques like batching, delta queries, and change notifications. The skill emphasizes secure practices, such as using managed identities and avoiding hardcoded secrets, while providing language-specific guidance for .NET, TypeScript/JavaScript, and Python environments.

What it does

  • Provides authentication patterns for various scenarios including daemon services, OBO, and managed identities.
  • Demonstrates fluent API usage for querying Microsoft 365 resources like Users, Mail, Teams, and SharePoint.
  • Explains efficient data retrieval techniques including pagination, field selection, and filtering.
  • Covers advanced integration patterns such as batch requests, delta queries, and webhook subscriptions.
  • Offers guidance on handling API throttling and implementing retry logic.
  • Provides language-specific setup instructions for .NET, Python, and TypeScript/JavaScript.

When to use it

  • When building applications that need to read or write data from Microsoft 365 services.
  • When determining the appropriate authentication flow for a specific application architecture.
  • When implementing efficient data synchronization using delta queries or change notifications.
  • When troubleshooting 403 permission errors or 429 throttling issues in Graph API calls.
  • When setting up a new project integration with the Microsoft Graph SDK.

Advantages

  • Standardizes authentication and API interaction patterns across different programming languages.
  • Promotes security best practices like least-privilege permissions and managed identities.
  • Reduces common integration errors through clear decision trees for auth and pagination.
  • Improves application performance by demonstrating batching and server-side filtering.
  • Ensures robust error handling by incorporating retry middleware for API throttling.

Usage examples

“How do I set up the Microsoft Graph SDK in a Python project using Managed Identity?”
The agent provides the necessary package installation commands and a code snippet using DefaultAzureCredential from the azure-identity library to initialize the GraphServiceClient.
“I need to list all unread messages for a user in C#. How do I filter and select specific fields?”
The agent provides a C# code example using the fluent API with QueryParameters to apply a filter for unread messages and select specific fields like subject and sender.
“What is the best way to handle pagination when fetching a large list of files from OneDrive?”
The agent explains the use of the PageIterator helper available in the SDK to automatically walk through pages using the @odata.nextLink.
“Which authentication flow should I use for a background service that accesses Teams data?”
The agent identifies the Client Credentials flow as the correct choice for daemon/background services and provides guidance on setting up the required application permissions.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/github/msgraph-sdk/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip msgraph-sdk.zip -d .agents/skills

Documentation by lovyjain

Microsoft Graph SDK

Use this skill when integrating Microsoft Graph into an application to access Microsoft 365 data and services.

Always ground implementation in the current Microsoft Graph SDK documentation and SDK version for the target language rather than relying on memory alone.

Determine the target language first

  1. Use the .NET workflow when the project contains .cs, .csproj, or .sln files, or when the user asks for C# guidance. Follow references/dotnet.md.

  2. Use the TypeScript / JavaScript workflow when the project contains package.json, .ts, or .js files, or when the user asks for Node.js / browser guidance. Follow references/typescript.md.

  3. Use the Python workflow when the project contains .py, pyproject.toml, or requirements.txt, or when the user asks for Python guidance. Follow references/python.md.

  4. If multiple languages are present, match the language of the files being edited or ask the user.

Always consult live documentation

Authentication — choose the right pattern

Selecting the wrong auth flow is the most common Graph integration mistake. Apply this decision tree before writing any auth code:

ScenarioFlow to use
Background service / daemon with no userClient credentials (app-only)
Agent or API acting on behalf of a signed-in userOn-Behalf-Of (OBO)
App running in Azure (Function, Container App, VM)Managed Identity (preferred over secrets)
CLI tool or local dev scriptDevice code or interactive browser
Single-page app (browser only)Authorization code + PKCE
  • Never use client credentials when a user context is required — Graph enforces this at the permission level (application vs. delegated).

  • Prefer DefaultAzureCredential in Azure-hosted apps; it tries managed identity first and falls back gracefully for local dev.

  • Never hardcode secrets. Use environment variables, Azure Key Vault, or the Secret Manager.

Core SDK usage patterns

Building the client

Always construct GraphServiceClient once and reuse it (it manages token caching internally).

Pass a credential from the Azure Identity library — never build raw HTTP clients manually.

Making calls
  • Use the fluent builder API: client.Users[userId].Messages.GetAsync(...).

  • Always await async calls.

  • Specify $select to limit returned fields — Graph returns large default payloads.

  • Use $filter server-side rather than filtering returned collections in memory.

  • Use $expand to fetch related resources in a single call when relationships are small.

Pagination

Graph paginates collections. Never assume all items arrive in one response:

  • Check for an @odata.nextLink on the response.

  • Use the SDK's PageIterator helper (available in all three SDKs) to walk pages automatically.

  • Set $top to control page size (max varies by resource, typically 999).

Advanced patterns

Batch requests

Combine up to 20 independent Graph calls into a single HTTP request using the $batch endpoint. Use batching when:

  • Initializing data for a dashboard or agent that needs multiple resources upfront.

  • Reducing latency in high-call-count operations.

Batch responses arrive out of order — match them by the id field you assigned each request.

Delta queries

Use delta queries to sync changes incrementally instead of polling full collections:

  • First call: GET /users/delta returns all items + a @odata.deltaLink.

  • Subsequent calls: use the deltaLink to receive only what changed since the last sync.

  • Supported on: users, groups, messages, calendar events, Teams channels, and more.

  • Store the deltaLink durably (database, blob) between sync runs.

Change notifications (webhooks)

Subscribe to resource changes with POST /subscriptions:

  • Graph delivers change events to your HTTPS notification URL.

  • Subscriptions expire — renew them before expirationDateTime (max varies by resource; typically 1–3 days for mail/calendar, up to 4230 minutes for users/groups).

  • Validate the subscription handshake: Graph sends a validationToken query parameter on creation — echo it back as plain text with HTTP 200.

  • Use lifecycle notifications (notificationUrl + lifecycleNotificationUrl) to handle missed events and reauthorization.

  • For high-volume scenarios prefer change notifications with resource data (requires additional encryption setup).

Throttling

Graph throttles aggressively. Always handle HTTP 429:

  • Read the Retry-After header — it specifies exact seconds to wait, not a fixed backoff.

  • The SDK's built-in retry middleware handles 429 automatically when configured; enable it explicitly.

  • Avoid fan-out patterns that hit Graph with hundreds of parallel requests; use batching or queuing instead.

Permissions

Get permissions right before writing auth code — wrong scopes result in 403 errors that are hard to debug later.

  • Application permissions run without a user (daemon / service). Require admin consent.

  • Delegated permissions run in the context of a signed-in user. Some require admin consent.

  • Request the minimum permissions needed. Graph's permission reference lists least-privilege options for every operation.

  • Use the Graph Explorer to test which permissions a call actually requires before coding.

  • In Azure app registrations: grant API permissions → Microsoft Graph → select type (Application or Delegated) → grant admin consent where required.

Common Graph resources — quick reference

GoalResource path
Get signed-in user's profileGET /me
List user's mailbox messagesGET /me/messages
Send an emailPOST /me/sendMail
List calendar eventsGET /me/events
Get user's OneDrive rootGET /me/drive/root/children
List Teams the user is inGET /me/joinedTeams
Post a Teams channel messagePOST /teams/{id}/channels/{id}/messages
List SharePoint site listsGET /sites/{siteId}/lists
Search across M365POST /search/query
List all users in tenant (app-only)GET /users
Get group membersGET /groups/{id}/members

In similar fashion, use the SDK's fluent API to navigate to these resources in code.

Workflow

  1. Determine the target language and read the matching reference file.

  2. Identify the auth scenario and choose the correct flow from the table above.

  3. Fetch current SDK docs and Graph Explorer examples before making implementation choices.

  4. Apply least-privilege permissions — confirm in the Graph permissions reference.

  5. Implement pagination from the start — don't assume single-page responses.

  6. Enable retry middleware for throttling from day one.

  7. For syncing scenarios, prefer delta queries over polling.

  8. Use the language-specific package names, auth provider setup, and code patterns from the chosen reference file.

Completion criteria

  • Auth flow matches the scenario (not defaulting to client credentials for user-context calls).

  • GraphServiceClient is constructed once and reused.

  • All collection reads handle pagination.

  • Throttling (429) is handled via retry middleware or explicit Retry-After logic.

  • Permissions are scoped to the minimum required.

  • No secrets or credentials are hardcoded.

  • Code matches current SDK version patterns for the selected language.

Files

references/python.md

Microsoft Graph SDK for Python

Use this reference when the target project is written in Python.

Authoritative sources

Packages

pip install msgraph-sdk azure-identity

Or in requirements.txt / pyproject.toml:

msgraph-sdk>=1.0.0
azure-identity>=1.15.0

Client setup

Managed Identity (Azure-hosted apps — preferred)
from azure.identity.aio import DefaultAzureCredential
from msgraph import GraphServiceClient

credential = DefaultAzureCredential()
graph_client = GraphServiceClient(credential)

The Python SDK is async-first (asyncio). Use azure.identity.aio (async variants), not azure.identity.

Client credentials (app-only / daemon)
import os
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient

credential = ClientSecretCredential(
    tenant_id=os.environ["AZURE_TENANT_ID"],
    client_id=os.environ["AZURE_CLIENT_ID"],
    client_secret=os.environ["AZURE_CLIENT_SECRET"],
)

graph_client = GraphServiceClient(credential)

Prefer CertificateCredential over ClientSecretCredential in production.

On-Behalf-Of (OBO) — agent / API acting as the signed-in user
from azure.identity.aio import OnBehalfOfCredential

# incoming_token is the bearer token from the caller
credential = OnBehalfOfCredential(
    tenant_id=os.environ["AZURE_TENANT_ID"],
    client_id=os.environ["AZURE_CLIENT_ID"],
    client_secret=os.environ["AZURE_CLIENT_SECRET"],
    user_assertion=incoming_token,
)

graph_client = GraphServiceClient(credential)

Construct a new GraphServiceClient per request for OBO — the credential is user-scoped.

Device code (CLI / local dev)
from azure.identity.aio import DeviceCodeCredential

credential = DeviceCodeCredential(
    client_id=os.environ["AZURE_CLIENT_ID"],
    tenant_id=os.environ["AZURE_TENANT_ID"],
)
graph_client = GraphServiceClient(credential, scopes=["User.Read", "Mail.Read"])

Common call patterns

All Graph SDK calls in Python are async. Always run inside an async context.

Get a resource with field selection
import asyncio
from msgraph.generated.me.me_request_builder import MeRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration

async def get_my_profile():
    query_params = MeRequestBuilder.MeRequestBuilderGetQueryParameters(
        select=["displayName", "mail", "jobTitle"]
    )
    config = RequestConfiguration(query_parameters=query_params)
    user = await graph_client.me.get(request_configuration=config)
    return user

asyncio.run(get_my_profile())
List messages with filter and select
from msgraph.generated.me.messages.messages_request_builder import MessagesRequestBuilder

async def get_unread_messages():
    query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
        filter="isRead eq false",
        select=["subject", "from", "receivedDateTime"],
        top=25,
        orderby=["receivedDateTime desc"],
    )
    config = RequestConfiguration(query_parameters=query_params)
    result = await graph_client.me.messages.get(request_configuration=config)
    return result
Pagination with PageIterator
from msgraph.generated.models.message import Message
from msgraph.core import PageIterator

async def get_all_messages():
    first_page = await graph_client.me.messages.get()
    all_messages: list[Message] = []

    async def process_message(message: Message) -> bool:
        all_messages.append(message)
        return True  # return False to stop early

    page_iterator = PageIterator(
        response=first_page,
        request_adapter=graph_client.request_adapter,
        constructor=Message,
    )
    await page_iterator.iterate(callback=process_message)
    return all_messages
Send an email
from msgraph.generated.models.message import Message
from msgraph.generated.models.item_body import ItemBody
from msgraph.generated.models.body_type import BodyType
from msgraph.generated.models.recipient import Recipient
from msgraph.generated.models.email_address import EmailAddress
from msgraph.generated.me.send_mail.send_mail_post_request_body import SendMailPostRequestBody

async def send_email():
    body = SendMailPostRequestBody(
        message=Message(
            subject="Hello from Graph",
            body=ItemBody(content_type=BodyType.Text, content="Test message"),
            to_recipients=[
                Recipient(email_address=EmailAddress(address="[email protected]"))
            ],
        )
    )
    await graph_client.me.send_mail.post(body)
Post a Teams channel message
from msgraph.generated.models.chat_message import ChatMessage
from msgraph.generated.models.item_body import ItemBody
from msgraph.generated.models.body_type import BodyType

async def post_channel_message(team_id: str, channel_id: str):
    message = ChatMessage(
        body=ItemBody(content_type=BodyType.Html, content="<b>Hello from Graph!</b>")
    )
    await graph_client.teams.by_team_id(team_id).channels.by_channel_id(channel_id).messages.post(message)

Batch requests

from kiota_http.middleware.options import ResponseHandlerOption
import json

async def batch_example():
    batch_body = {
        "requests": [
            {"id": "1", "method": "GET", "url": "/me"},
            {"id": "2", "method": "GET", "url": "/me/messages?$top=5&$select=subject"},
        ]
    }
    # Use the raw HTTP client for batch
    response = await graph_client.request_adapter.send_primitive_async(
        # Alternatively, use the requests library with a token from the credential
    )

For batch in Python, it's often simpler to use httpx with an acquired token when the batch helper is not yet fully supported:

import httpx
from azure.identity.aio import ClientSecretCredential

async def batch_with_httpx(credential):
    token = await credential.get_token("https://graph.microsoft.com/.default")
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://graph.microsoft.com/v1.0/$batch",
            headers={"Authorization": f"Bearer {token.token}"},
            json={
                "requests": [
                    {"id": "1", "method": "GET", "url": "/me"},
                    {"id": "2", "method": "GET", "url": "/me/messages?$top=5"},
                ]
            },
        )
    return response.json()

Delta queries

async def delta_sync(stored_delta_link: str | None = None):
    if stored_delta_link:
        # Use delta link directly
        response = await graph_client.request_adapter.send_async(...)
    else:
        response = await graph_client.users.delta.get()

    users = []
    async def collect(user):
        users.append(user)
        return True

    page_iterator = PageIterator(response=response, request_adapter=graph_client.request_adapter, constructor=...)
    await page_iterator.iterate(callback=collect)

    delta_link = page_iterator.delta_link  # store this for next run
    return users, delta_link

Throttling / retry

The SDK's HTTP transport handles 429 retry automatically when using the default GraphClientFactory. For explicit control:

import asyncio
import httpx

async def call_with_retry(graph_client, call_fn, max_retries=5):
    for attempt in range(max_retries):
        try:
            return await call_fn()
        except Exception as e:
            if "429" in str(e):
                retry_after = int(getattr(e, "retry_after", 10))
                await asyncio.sleep(retry_after)
            else:
                raise

Python-specific guidance

  • The Python Graph SDK is async-first — use asyncio.run() or an async framework (FastAPI, aiohttp).

  • Always use azure.identity.aio (not azure.identity) for async contexts.

  • Close credentials when done: await credential.close() or use as async context managers.

  • Python SDK model classes use snake_case for properties (Graph JSON uses camelCase — the SDK maps automatically).

  • Use asyncio.gather() for concurrent but independent Graph calls (mind throttling limits).

  • For FastAPI: use lifespan events to init GraphServiceClient once and close the credential on shutdown.

# FastAPI integration example
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    credential = DefaultAzureCredential()
    app.state.graph_client = GraphServiceClient(credential)
    yield
    await credential.close()

app = FastAPI(lifespan=lifespan)

Requirements and compatibility

Written for: GitHub Copilot

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of lovyjainlovyjain
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/msgraph-sdk · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
lovyjain

AutoGineer is not affiliated with or endorsed by lovyjain or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download msgraph-sdk.zip