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.
import { Client } from "@microsoft/microsoft-graph-client";
Include lib/graph-js-sdk-web.js
in your page.
<script type="text/javascript" src="graph-js-sdk-web.js"></script>
Incase if your application ships with es6-promise and isomorphic-fetch just use lib/graph-js-sdk-core.js
<script type="text/javascript" src="graph-js-sdk-core.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 (MSALAuthenticationProvider) 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).
Note: MSAL is supported only for frontend applications, for server-side authentication you have to implement your own AuthenticationProvider. Refer implementing 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>
const clientId = "your_client_id"; // Client Id of the registered application
const callback = (errorDesc, token, error, tokenType) => {};
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const options = {
redirectUri: "Your redirect URI",
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#initialization-of-msal
const userAgentApplication = new Msal.UserAgentApplication(clientId, undefined, callback, options);
const authProvider = new MicrosoftGraph.MSALAuthenticationProvider(userAgentApplication, graphScopes);
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 { MSALAuthenticationProvider } from "./node_modules/@microsoft/microsoft-graph-client/lib/src/MSALAuthenticationProvider";
const clientId = "your_client_id"; // Client Id of the registered application
const callback = (errorDesc, token, error, tokenType) => {};
// An Optional options for initializing the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#configuration-options
const options = {
redirectUri: "Your redirect URI",
};
const graphScopes = ["user.read", "mail.send"]; // An array of graph scopes
// Initialize the MSAL @see https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics#initialization-of-msal
const userAgentApplication = new UserAgentApplication(clientId, undefined, callback, options);
const authProvider = new MSALAuthenticationProvider(userAgentApplication, scopes);
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: "[email protected]",
},
},
],
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
- Angular.js sample using the JavaScript client library
- Node.js sample using the JavaScript client library
- 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 [email protected] 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 [email protected] with any additional questions or comments.