Microsoft 365 API
| title | description | updated_date |
|---|---|---|
| Microsoft 365 API | How to set up Microsoft 365 API access for your organization. | 2025-10-24T16:45:21Z |
What we need
[] Client ID [] Client Secret [] Tenant ID [] API Token
This guide walks through the process of setting up Microsoft Graph API (REST API) access to Microsoft 365 services, including user data, Outlook emails, calendars, slides etc.
Terminology/Product names
Office 365
Office 365 includes apps such as Outlook, Word, Excel, and PowerPoint, along with services such as Exchange, OneDrive, and SharePoint. (Microsoft Teams is an optional add-on.)
Microsoft 365
Microsoft 365 includes the apps from Office 365 along with identity & access management, device & application management and cyberthreat protections. (Microsoft Teams is an optional add-on.)
Prerequisites
Before you begin, ensure you have:
- A Microsoft 365 administrator account with
Global Administratorprivileges or at least theCloud Application Administratorrole - Access to the Microsoft Entra admin center
- A Microsoft 365 subscription with the services you want to access
Step 1: Register the application with the Microsoft identity platform
To call Microsoft Graph, an app must obtain an access token from the Microsoft identity platform. Therefore we first need to register the app with the identity platform.
Sign in to the Entra admin center
- Go to Microsoft Entra admin center
- Sign in with the administrator account
Select the desired tenant
- If you have access to multiple tenants, use the Settings icon in the top menu to switch to the tenant in which you want to register the application from the Directories + subscriptions menu.
Create a new App registration
- Browse to
Entra ID > App registrationsand selectNew registration - Enter a display Name for your application.
- Specify who can use the application in the Supported account types section. See the supported account types listed in the documentation section Register an Application under 5.
- you can keep the pre-selected default value:
Accounts in this organizational directory only
- you can keep the pre-selected default value:
- Don’t enter anything for Redirect URI.
- Select Register to complete the initial app registration.
- Browse to
Note important information
- After registration, you’ll be taken to the application’s overview page
- Note the following values (you’ll need these later):
- Application (client) ID which uniquely identifies your application in the Microsoft cloud ecosystem, across all tenants.
- Directory (tenant) ID
Add credentials so that the app can authenticate itself
- Go to
Certificates & secretsin the app registration window of the Microsoft Entra admin center - There are 3 options (Add a public key, Add a client secret/application password and Add a federated credential using workload identity federation )
- click on
Client secrets>New client secret - Add a description for your client secret.
- Select an expiration for the secret (max 24 months)
- Select Add.
- IMPORTANT: Record the secret’s value for use in your client application code. This secret value is NEVER DISPLAYED AGAIN after you leave this page.
- click on
- Go to
Step 2: Set up app-only access to Microsoft Graph with API permissions
- Configure permissions for Microsoft Graph
Microsoft Graph exposes application permissions for apps that call Microsoft Graph with their own identity. These permissions always require administrator consent. To configure application permissions for the app in the app registrations experience on the Microsoft Entra admin center, follow these steps:
- On the application’s
API permissionspage, chooseAdd a permission. - Select
Microsoft Graph> selectApplication permissions. - In the
Select Permissionsdialog, choose the permissions to configure to the app:- For Users:
User.Read.All(Allows the app to read user profiles without a signed in user.)
- For Groups:
Group.Read.All(Allows the app to read group properties and memberships, and read conversations for all groups, without a signed-in user.)
- For Outlook Emails:
Mail.Read(Allows the app to read mail in all mailboxes without a signed-in user.)
- For Outlook Calendars access:
Calendars.Read(Allows the app to read events of all calendars without a signed-in user.)
- For OneDrive and SharePoint access:
Sites.Read.All(Allows the app to read documents and list items in all site collections without a signed in user.)Files.Read.All(Allows the app to read all files in all site collections without a signed in user.)
- For OneDrive and SharePoint audit logs:
AuditLogsQuery-OneDrive.Read.All(Allows the app to read and query audit logs from OneDrive workload, without a signed-in user)AuditLogsQuery-SharePoint.Read.All(Allows the app to read and query audit logs from SharePoint workload, without a signed-in user)- FYI for ALL audit logs:
AuditLog.Read.All(Allows the app to read and query your audit log activities, without a signed-in user.)
- For Users:
- Once you have added all the required permissions, click the Add permissions button.
- On the application’s
API usage
Token request
Access token request with a shared secret/application password
Acquire a token by sending a POST request to:
// Line breaks are for legibility only.
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=535fb089-9ff3-47b6-9bfb-4f1264799865
&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
&client_secret=qWgdYA....L1qKv5bPX
&grant_type=client_credentials
- With these parameters:
client_id: The application ID that the Azure app registration portal assigned when you registered your app.scope: https://graph.microsoft.com/.defaultclient_secret: The client secret that you generated for your app in the app registration portal. Ensure that it’s URL encoded.grant_type: Must beclient_credentials
Use the access token to call Microsoft Graph
Once you have obtained an access token, you can use it to call the Microsoft Graph API:
Make API requests
- Include the access token in the Authorization header, in the example below we are calling the users API endpoint:
GET https://graph.microsoft.com/v1.0/users HTTP/1.1 Authorization: Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw Host: graph.microsoft.comExample API endpoints General structure:
https://graph.microsoft.com/{version}/{resource}?{query-parameters}- Users:
https://graph.microsoft.com/v1.0/users - Teams:
https://graph.microsoft.com/v1.0/teams - Emails:
https://graph.microsoft.com/v1.0/users/{user-id}/messages - Calendars:
https://graph.microsoft.com/v1.0/users/{user-id}/calendars - Calendar Events:
https://graph.microsoft.com/v1.0/users/{user-id}/events
- Users:
Security Best Practices
Store secrets securely
- Never hardcode client secrets in your application
- Use secure secret management solutions (e.g., Azure Key Vault, environment variables)
Implement token management
- Store tokens securely
- Refresh access tokens when they expire
- Validate tokens before use
Use the principle of least privilege
- Only request permissions your application actually needs
- Use delegated permissions instead of application permissions when possible
Implement proper error handling
- Handle authentication and authorization errors gracefully
- Implement retry logic with exponential backoff for rate limiting
Troubleshooting Common Issues
“Invalid client” error
- Verify your client ID and client secret are correct
- Ensure the application is properly registered
“Invalid scope” error
- Check that the requested permissions are properly formatted
- Verify the permissions are available for your application type
“Insufficient privileges” error
- Ensure admin consent has been granted for the required permissions
- Verify the authenticated user has the necessary roles
“Invalid grant” error
- Check that the redirect URI exactly matches the registered one
- Ensure authorization codes are used only once and promptly
Item Checklist for Integration
- Application (client) ID
- Directory (tenant) ID
- Client secret
- List of required permissions/scopes
- Administrator account with consent privileges
Additional Resources
- Microsoft Graph documentation
- Microsoft identity platform documentation
- Microsoft Graph Explorer (for testing API calls)
- Microsoft Authentication Library (MSAL) (for implementing authentication)
Microsoft 365 Audit Log for Files
This section provides guidance on accessing Microsoft 365 file audit logs through the Microsoft Graph API.
What We Need
- Microsoft 365 Tenant with:
- Microsoft Purview Audit (Standard or Premium) enabled
- Azure AD App Registration (or use delegated permissions)
- Graph API Permissions:
AuditLogsQuery.Read.Allor more granular:AuditLogsQuery-SharePoint.Read.AllAuditLogsQuery-OneDrive.Read.All
- These require admin consent
- Role in Microsoft 365:
- You must be in the
Compliance AdministratororAudit Readerrole
- You must be in the
- An App registered in Azure
- Application (client) ID
- Directory (tenant) ID
- Client secret
Permissions
Auditing data can be accessed through Microsoft Purview Audit Search API via the following permissions, which are classified at a Microsoft 365 service level.
| Microsoft 365 service | Application Permission |
|---|---|
| Microsoft OneDrive | AuditLogsQuery-OneDrive.Read.All |
| Microsoft Exchange | AuditLogsQuery-Exchange.Read.All |
| Microsoft SharePoint | AuditLogsQuery-SharePoint.Read.All |
| Data Loss Protection for Endpoint | AuditLogsQuery-Endpoint.Read.All |
| Microsoft Dynamics CRM | AuditLogsQuery-CRM.Read.All |
| Microsoft Entra | AuditLogsQuery-Entra.Read.All |
| All Audit Logs | AuditLogsQuery.Read.All |
Special Considerations
| Issue | Explanation |
|---|---|
| Audit logs not enabled? | Make sure Purview audit is turned on in Microsoft 365 compliance portal |
Using /v1.0? | File audit logs are not yet in v1.0 — use /beta |
| Need compliance role | You may need to be in Compliance Administrator or Audit Reader roles |
API Access Setup
Register an Application in Azure
- Follow the steps in “Step 1: Register the application with the Microsoft identity platform” above
- Note your Application (client) ID and Directory (tenant) ID
Configure API Permissions
- In Azure Portal → App Registration → Your App → API permissions
- Add the following under Microsoft Graph → Application permissions:
AuditLogsQuery.Read.All(or the more granular permissions listed above)
- Click Grant admin consent
Generate Client Secret
- In Azure Portal → App Registration → Your App → Certificates & secrets
- Create a new client secret and save it securely
Using the Audit Log API
Get an Access Token
curl -X POST https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "client_id=<client_id>" \ -d "scope=https://graph.microsoft.com/.default" \ -d "client_secret=<client_secret>" \ -d "grant_type=client_credentials"Call Audit Search API (Beta)
POST https://graph.microsoft.com/beta/security/alerts/runAuditSearch Authorization: Bearer <access_token> Content-Type: application/jsonExample request body:
{ "contentQuery": "SharePoint AND FileName:*.docx", "startTime": "2023-01-01T00:00:00Z", "endTime": "2023-01-31T23:59:59Z" }Get the Job Status
The response will return a job ID:
{ "searchId": "abc123-guid", "status": "inProgress" }Poll the status with:
GET https://graph.microsoft.com/beta/security/alerts/getAuditSearchResults(searchId='abc123-guid')Repeat until you get:
{ "status": "completed", "results": [ ... ] }
Troubleshooting
Access Denied Errors
- Verify that admin consent has been granted for the required permissions
- Confirm you have the necessary compliance roles assigned
No Data Returned
- Check that Purview audit is enabled in the Microsoft 365 compliance portal
- Verify your date range is correct
- Ensure you’re using the
/betaendpoint, not/v1.0
API Errors
- Validate your access token is valid and not expired
- Check that your query syntax is correct
Additional Resources
- Microsoft Graph API - Audit Core Root
- Microsoft Purview Audit
- Microsoft Graph Explorer (for testing API calls)