Getting started overview
Integrating with Microsoft Graph API requires a structured approach that begins with registering your application and ends with making an authenticated request. This guide outlines the essential steps to get your first call working. The core process involves:
- Application Registration: Creating a unique identity for your application within the Microsoft Entra admin center.
- Permission Configuration: Defining what data and actions your application can access within Microsoft 365.
- Authentication Flow: Implementing an OAuth 2.0 flow to acquire an access token.
- Making a Request: Using the acquired token to call a Microsoft Graph API endpoint.
Microsoft Graph API utilizes standard OAuth 2.0 authorization flows for securing access to resources. Understanding the appropriate flow for your application type (e.g., web application, mobile app, daemon service) is crucial for a successful integration. Microsoft provides a comprehensive API reference detailing available endpoints and operations.
The following table provides a quick reference for the initial setup steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Sign Up/Log In | Access a Microsoft account with Azure subscription or a Microsoft 365 developer program account. | Microsoft Graph documentation |
| 2. Register Application | Create a new application registration to obtain client ID and tenant ID. | Microsoft Entra admin center |
| 3. Configure Permissions | Define the API permissions your application requires (e.g., User.Read, Mail.Read). |
Microsoft Entra admin center |
| 4. Obtain Access Token | Implement an OAuth 2.0 flow to get an access token. | Your application's backend or client-side code |
| 5. Make API Call | Construct and send an HTTP request to a Graph API endpoint. | Your application's backend or client-side code |
Create an account and get keys
To begin, you need a Microsoft account with access to an Azure subscription or a Microsoft 365 developer program account. The Microsoft 365 Developer Program provides a free sandbox environment, which is ideal for testing and development without impacting production data. Once you have a suitable account, follow these steps to register your application and obtain necessary credentials:
- Navigate to the Microsoft Entra admin center: Sign in to the Microsoft Entra admin center with your developer account.
- Register a new application:
- In the left-hand navigation pane, select Identity > Applications > App registrations.
- Click New registration.
- Provide a Name for your application (e.g., "My Graph Test App").
- Choose the Supported account types. For most development scenarios, "Accounts in any organizational directory (Any Microsoft Entra ID directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)" is a flexible option.
- For Redirect URI (optional), select the appropriate platform (e.g., "Web" for a web application). If you are using the Graph Explorer for initial testing, you can typically leave this blank or use
https://localhostfor local development. For a full application, specify the URI where authentication responses will be sent. - Click Register.
- Record application details: After registration, you'll be redirected to the application's overview page. Note down the Application (client) ID and Directory (tenant) ID. These are crucial for authenticating your application.
- Generate a client secret (for confidential client applications):
- In the left-hand navigation for your application, select Certificates & secrets.
- Under Client secrets, click New client secret.
- Add a Description and set an Expires duration.
- Click Add.
- Immediately copy the Value of the client secret. This value is only shown once and cannot be retrieved later. Store it securely.
- Configure API permissions:
- In the left-hand navigation for your application, select API permissions.
- Click Add a permission.
- Select Microsoft Graph.
- Choose the type of permissions your application needs (Delegated permissions for user-context access or Application permissions for daemon services).
- Select the specific permissions required (e.g.,
User.Readto read the signed-in user's profile). - Click Add permissions.
- For application permissions or certain delegated permissions, an administrator might need to grant consent. Click Grant admin consent for [your tenant name] if available.
Your first request
Once your application is registered and permissions are configured, you can make your first API request. This example uses the Graph Explorer, a tool provided by Microsoft, for simplicity. For programmatic access, you would typically use an SDK or an HTTP client library in your chosen programming language.
Using Graph Explorer
- Access Graph Explorer: Open Graph Explorer in your web browser.
- Sign in: Click the Sign in to Graph Explorer button and sign in with the Microsoft account associated with your registered application and its permissions.
- Select permissions: After signing in, ensure the necessary permissions are granted within Graph Explorer. Click on the Modify permissions tab and consent to the permissions required for your test (e.g.,
User.Read). - Construct your request: In the HTTP request composer:
- Select the HTTP method:
GET. - Enter the request URL:
https://graph.microsoft.com/v1.0/me. This endpoint retrieves the profile of the signed-in user.
- Select the HTTP method:
- Run the query: Click the Run query button.
- View the response: The response pane will display the JSON data containing the signed-in user's profile information.
Programmatic Example (JavaScript with Microsoft Graph SDK)
For a programmatic approach, you would use an authentication library (like MSAL.js) to obtain an access token and then use the Microsoft Graph SDK to make requests. This example demonstrates fetching the signed-in user's profile.
// 1. Install Microsoft Authentication Library (MSAL) and Microsoft Graph JavaScript SDK
// npm install @azure/msal-browser @microsoft/microsoft-graph-client
import * as msal from "@azure/msal-browser";
import { Client } from "@microsoft/microsoft-graph-client";
import { AuthCodeMSALBrowserAuthenticationProvider }
from "@microsoft/microsoft-graph-client/authProviders/authCodeMsalBrowser";
const msalConfig = {
auth: {
clientId: "YOUR_CLIENT_ID", // Application (client) ID from App Registration
authority: "https://login.microsoftonline.com/YOUR_TENANT_ID", // Or common for multi-tenant
redirectUri: "http://localhost:3000", // Your application's redirect URI
},
cache: {
cacheLocation: "sessionStorage", // Or localStorage
storeAuthStateInCookie: false,
},
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
const scopes = ["User.Read"]; // Permissions requested
const authProvider = new AuthCodeMSALBrowserAuthenticationProvider(
msalInstance,
{
account: msalInstance.getActiveAccount(), // Or retrieve account via login
scopes: scopes,
interactionType: msal.InteractionType.Popup, // Or Redirect
}
);
const graphClient = Client.withMiddleware({
authProvider: authProvider
});
async function getMe() {
try {
// Ensure user is logged in and has an active account
if (!msalInstance.getActiveAccount()) {
await msalInstance.loginPopup({ scopes: scopes });
}
const user = await graphClient.api('/me').get();
console.log(user);
} catch (error) {
console.error("Error fetching user profile:", error);
}
}
getMe();
Replace YOUR_CLIENT_ID and YOUR_TENANT_ID with the values obtained during application registration. The example assumes a user is logged in; for a full implementation, you would handle user login and account selection.
Common next steps
After successfully making your first request, consider these common next steps to further develop your integration:
- Explore more endpoints: Review the Microsoft Graph API reference to understand the breadth of available data and operations across Microsoft 365, Windows 365, and Enterprise Mobility + Security.
- Implement different authentication flows: Depending on your application type (e.g., client-side web app, mobile app, background service), you may need different OAuth 2.0 flows. Consult the Microsoft identity platform authentication flows documentation.
- Use an SDK: For most programming languages, Microsoft provides SDKs that simplify API calls and token management. Refer to the Microsoft Graph SDK documentation for your preferred language.
- Handle pagination and batching: For large datasets, learn how to handle pagination and consider JSON batching for optimizing multiple requests.
- Implement webhooks (change notifications): For real-time updates, explore Microsoft Graph webhooks to receive notifications when data changes.
- Error handling and logging: Implement robust error handling and logging to diagnose and resolve issues efficiently.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips:
- Invalid or expired access token: Ensure your access token is current and correctly included in the
Authorization: Bearerheader. Tokens have a limited lifespan and must be refreshed. - Insufficient permissions: Double-check that your application registration has all the necessary API permissions configured in the Microsoft Entra admin center. If using delegated permissions, ensure the signed-in user also has the required permissions.
- Admin consent not granted: For some permissions, particularly application permissions or high-privilege delegated permissions, an administrator must explicitly grant consent for your application.
- Incorrect API endpoint or version: Verify that the URL you are calling is correct and uses the appropriate API version (e.g.,
v1.0orbeta). - Network issues: Confirm that your application can reach the Microsoft Graph API endpoints.
- Client secret issues: If using a client secret, ensure you copied the correct value immediately after generation and that it hasn't expired.
- Consult Graph Explorer: If a programmatic call fails, try the same request in Graph Explorer. If it works there, the issue is likely in your code's authentication or request construction. If it fails in Graph Explorer, the problem might be with permissions or the endpoint itself.
- Review Microsoft Graph documentation: The official Microsoft Graph documentation contains detailed guides and troubleshooting sections for common errors.