The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that can be used server-side and in the browser.
Looking for IntelliSense on models (Users, Groups, etc.)? Check out the Microsoft Graph Types repository!
npm install @microsoft/microsoft-graph-client
import @microsoft/microsoft-graph-client
into your module and also you will need polyfills for fetch like isomorphic-fetch.
import "isomorphic-fetch";
import { Client } from "@microsoft/microsoft-graph-client";
Include graph-js-sdk.js in your HTML page.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@microsoft/microsoft-graph-client/lib/graph-js-sdk.js"></script>
In case your browser doesn't have support for Fetch [support] or Promise [support], you need to use polyfills like github/fetch for fetch and es6-promise for promise.
<!-- polyfilling promise -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"></script>
<!-- polyfilling fetch -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/whatwg-fetch/dist/fetch.umd.min.js"></script>
<!-- depending on your browser you might wanna include babel polyfill -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@babel/polyfill@7.4.4/dist/polyfill.min.js"></script>
Register your application to use Microsoft Graph API using one of the following supported authentication portals:
- Microsoft Application Registration Portal: Register a new application that works with Microsoft Accounts and/or organizational accounts using the unified V2 Authentication Endpoint.
- Microsoft Azure Active Directory: Register a new application in your tenant's Active Directory to support work or school users for your tenant or multiple tenants.
The Microsoft Graph JavaScript Client Library has an adapter implementation (ImplicitMSALAuthenticationProvider) for MSAL (Microsoft Authentication Library) which takes care of getting the accessToken
. MSAL library does not ship with this library, user has to include it externally (For including MSAL, refer this).
Important Note: MSAL is supported only for frontend applications, for server-side authentication you have to implement your own AuthenticationProvider. Learn how you can create a Custom Authentication Provider.
Refer devDependencies in package.json for the compatible msal version and update that version in below.
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/<version>/js/msal.min.js"></script>
// Configuration options for MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL.js-1.0.0-api-release#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new Msal.UserAgentApplication(msalConfig);
const options = new MicrosoftGraph.MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new MicrosoftGraph.ImplicitMSALAuthenticationProvider(msalApplication, options);
Refer devDependencies in package.json for the compatible msal version and update that version in below.
npm install msal@<version>
import { UserAgentApplication } from "msal";
import { ImplicitMSALAuthenticationProvider } from "@microsoft/microsoft-graph-client/lib/src/ImplicitMSALAuthenticationProvider";
import { MSALAuthenticationProviderOptions } from '@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProviderOptions';
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const msalConfig = {
auth: {
clientId: "your_client_id", // Client Id of the registered application
redirectUri: "your_redirect_uri",
},
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Important Note: This library implements loginPopup and acquireTokenPopup flow, remember this while initializing the msal
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js#1-instantiate-the-useragentapplication
const msalApplication = new UserAgentApplication(msalConfig);
const options = new MSALAuthenticationProviderOptions(graphScopes);
const authProvider = new ImplicitMSALAuthenticationProvider(msalApplication, options);
User can integrate own preferred authentication library by implementing IAuthenticationProvider
interface. Refer implementing Custom Authentication Provider.
An instance of the Client class handles requests to Microsoft Graph API and processing the responses. To create a new instance of this class, you need to provide an instance of IAuthenticationProvider
which needs to be passed as a value for authProvider
key in ClientOptions
to a static initializer method Client.initWithMiddleware
.
const options = {
authProvider, // An instance created from previous step
};
const Client = MicrosoftGraph.Client;
const client = Client.initWithMiddleware(options);
import { Client } from "@microsoft/microsoft-graph-client";
const options = {
authProvider, // An instance created from previous step
};
const client = Client.initWithMiddleware(options);
For more information on initializing client, refer this document.
Once you have authentication setup and an instance of Client, you can begin to make calls to the service. All requests should be start with client.api(path)
and end with an action.
Getting user details
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
Sending an email to the recipients
// Construct email object
const mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [
{
emailAddress: {
address: "example@example.com",
},
},
],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html",
},
};
try {
let response = await client.api("/me/sendMail").post({ message: mail });
console.log(response);
} catch (error) {
throw error;
}
For more information, refer: Calling Pattern, Actions, Query Params, API Methods and more.
- Batching
- Large File Upload Task
- Page Iterator
- Actions
- Query Parameters
- Other APIs
- Getting Raw Response
We'd love to get your feedback about the Microsoft Graph JavaScript client library. You can send your questions and suggestions to us in the Issues section of this repository.
Please see the contributing guidelines.
- Microsoft Graph website
- Microsoft Graph TypeScript types
- Build Angular single-page apps with Microsoft Graph
- Build Node.js Express apps with Microsoft Graph
- Office Dev Center
See Third Party Notices for information on the packages that are included in the package.json
If you find a security issue with our libraries or services please report it to secure@microsoft.com with as much detail as possible. Your submission may be eligible for a bounty through the Microsoft Bounty program. Please do not post security issues to GitHub Issues or any other public site. We will contact you shortly upon receiving the information. We encourage you to get notifications of when security incidents occur by visiting this page and subscribing to Security Advisory Alerts.
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");
This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.