Microsoft Graph API

Microsoft Graph is the single REST API for Microsoft 365 data: mail, calendar, OneDrive, Teams and the directory. How it works, and how I use it from stdlib Python to export my mailbox and OneDrive files.

Microsoft Graph is Microsoft's API for everything in Microsoft 365 and Entra ID (the directory formerly called Azure AD). 1 endpoint, https://graph.microsoft.com, gives REST access to a user's mail, calendar, contacts, OneDrive and SharePoint files, Teams, To Do, Planner and OneNote, plus the users, groups and devices of the organisation.

If your company runs on Microsoft 365, Graph is how you get your own work data into your own tools, without screen scraping.

What it covers

Area Examples
Mail /me/messages, /me/mailFolders, the raw MIME of a message
Calendar /me/events, /me/calendarView, free/busy
Files /me/drive, SharePoint sites and document libraries
Teams Chats, channels, messages, meetings
People /me/people (who you work with), /users, /me/manager
Tasks and notes To Do, Planner, OneNote
Security and devices Entra ID, Intune, audit logs (admin territory)

2 versions run side by side: v1.0 for production and beta for preview endpoints that can change.

Graph is free to call. You pay for the Microsoft 365 licences, not for the API. A few APIs that export data in bulk (some Teams export APIs) are metered.

How authentication works

Every call carries an OAuth 2.0 token from the Microsoft identity platform. 2 kinds of permission:

Type Who acts Who consents
Delegated An app, on behalf of a signed-in user The user, for low-risk scopes. An admin for the rest
Application An app on its own, no user Always a tenant admin

For a personal script against your own data, delegated permissions are the route. The scopes that need no admin consent in most tenants include User.Read, Mail.Read, Calendars.Read, Files.Read, People.Read and User.ReadBasic.All. Your tenant can still block user consent entirely: that's an IT setting, and Graph will tell you with an AADSTS error.

Device code flow suits a script with no web server. The script asks for a code, you open a Microsoft URL in any browser, type the code and sign in, and the script receives the token. Add offline_access to the scopes and you get a refresh token, so later runs are unattended.

The app registration. Normally you register your own app in Entra ID. For a script, Microsoft's own public client app, Microsoft Graph Command Line Tools, works too. It's the client the Graph PowerShell SDK uses, so many tenants already allow it.

The features that make it practical

  • Delta queries. Call /delta on a folder once, store the deltaLink it returns, and every later call gets only what changed. A daily mailbox sync takes seconds instead of re-reading 10,000s of messages.
  • Paging. Results come in pages with an @odata.nextLink. Follow it until it's gone.
  • $select, $filter, $top. OData query options keep responses small.
  • Change notifications. Webhooks that tell you when a resource changes, if you can host an HTTPS endpoint.
  • Batching. Up to 20 requests in 1 $batch call.
  • Graph Explorer. A web console to try any call with your own account before writing code.

A minimal client in stdlib Python

No SDK, no msal: the device code flow and a delta sync are a few urllib calls.

import json
import time
import urllib.error
import urllib.parse
import urllib.request

CLIENT_ID = "14d82eec-204b-4c2f-b7e8-296a70dab67e"  # Microsoft Graph Command Line Tools
LOGIN = "https://login.microsoftonline.com/organizations/oauth2/v2.0"
SCOPE = "Mail.Read offline_access"


def post_form(url: str, data: dict) -> dict:
    body = urllib.parse.urlencode(data).encode()
    try:
        with urllib.request.urlopen(urllib.request.Request(url, body)) as r:
            return json.load(r)
    except urllib.error.HTTPError as e:
        return json.load(e)  # pending sign-in comes back as a 400 with an error code


def device_code_login() -> dict:
    """Sign in once in the browser; returns access and refresh tokens."""
    flow = post_form(f"{LOGIN}/devicecode", {"client_id": CLIENT_ID, "scope": SCOPE})
    print(flow["message"])  # "To sign in, open https://microsoft.com/devicelogin and enter the code ..."
    while True:
        time.sleep(flow["interval"])
        token = post_form(f"{LOGIN}/token", {
            "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
            "client_id": CLIENT_ID, "device_code": flow["device_code"]})
        if "access_token" in token:
            return token
        if token.get("error") != "authorization_pending":
            raise RuntimeError(token.get("error_description"))


def get(url: str, access_token: str) -> dict:
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {access_token}"})
    with urllib.request.urlopen(req) as r:
        return json.load(r)

For a delta sync, start at /me/mailFolders/inbox/messages/delta, follow each @odata.nextLink, and save the @odata.deltaLink from the last page for the next run.

Gotchas

  • Throttling. Graph answers 429 with a Retry-After header. Honour it: retry storms make the limit worse. Mail has a limit per mailbox, not only per app.
  • Token lifetime. Access tokens last about 1 hour. Refresh before each run and store the new refresh token, because it rotates.
  • Consent errors are tenant policy. The same script works in one company and fails in another. Nothing in your code fixes AADSTS65001 or a blocked app: ask IT.
  • /users with basic scope returns names and emails, and may refuse job title and department. /me/people carries those fields for the people you work with.
  • Deleted is not gone from your copy. A delta sync reports deletions as @removed. Decide whether your local copy follows them or keeps the file.

How I use it in NicAI

3 scripts in my shared tools folder use Graph with my work Microsoft 365 account. All 3 are standard library Python, use the device code flow with the Microsoft Graph Command Line Tools client, and store the refresh token locally so they run unattended.

Script Scope What it does
m365_export.py Mail.Read Exports the mailbox to .eml files with delta queries
onedrive_attachments.py Files.Read Downloads new files from the OneDrive folder where Outlook saves attachments
directory_export.py User.ReadBasic.All, People.Read 1-off export of the company address book to CSV, JSON and Excel

Mailbox export. The first run reads every header in each folder and saves a delta link per folder in SQLite. Later runs ask Graph for changes only. The export only grows: a message I delete in Outlook keeps its local .eml, and a message I move moves with it. The .eml files feed my local tools, such as an address book built from the email signatures.

OneDrive attachments. A LaunchAgent runs the script every 15 minutes. Each file downloads once. A file I delete or move locally doesn't come back unless its content changes in OneDrive, and nothing is ever deleted on either side. The files then go through my intake pipeline, see Intakee: the app that files every new file.

Address book. 2 sources merged on email: /users for every account in the tenant, /me/people for the job titles and departments of the people I actually work with.

Where Graph isn't the answer. Writes (sending mail, invitations) and my work chat go through my agent browser instead, see BrowserOS - a local browser for AI agents. My work calendar reaches my booking page as a published ICS feed, see cal.eu - Cal.com hosted in Europe.

Further reading

NicAI
Written by NicAI, Nic's AI assistant, for his personal knowledge base. Researched and drafted by the model, not hand-written by Nic. Verify anything you plan to act on.