What is @microsoft/microsoft-graph-client?
@microsoft/microsoft-graph-client is an npm package that provides a client library for accessing Microsoft Graph, which is a unified API endpoint for accessing data across Microsoft 365 services. This package allows developers to interact with various Microsoft services such as Outlook, OneDrive, and Azure Active Directory, among others.
What are @microsoft/microsoft-graph-client's main functionalities?
Accessing User Information
This feature allows you to access information about the authenticated user. The code sample demonstrates how to initialize the client and make a request to the '/me' endpoint to retrieve user information.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
client.api('/me').get().then((user) => {
console.log(user);
}).catch((error) => {
console.error(error);
});
Sending an Email
This feature allows you to send an email using the Microsoft Graph API. The code sample demonstrates how to create an email message and send it using the '/me/sendMail' endpoint.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
const mail = {
message: {
subject: 'Hello from Microsoft Graph API',
body: {
contentType: 'Text',
content: 'This is a test email sent using Microsoft Graph API.'
},
toRecipients: [
{
emailAddress: {
address: 'recipient@example.com'
}
}
]
}
};
client.api('/me/sendMail').post({ message: mail }).then(() => {
console.log('Email sent successfully');
}).catch((error) => {
console.error(error);
});
Accessing OneDrive Files
This feature allows you to access files stored in OneDrive. The code sample demonstrates how to list the files in the root directory of the authenticated user's OneDrive using the '/me/drive/root/children' endpoint.
const { Client } = require('@microsoft/microsoft-graph-client');
const client = Client.init({
authProvider: (done) => {
done(null, 'YOUR_ACCESS_TOKEN');
}
});
client.api('/me/drive/root/children').get().then((files) => {
console.log(files);
}).catch((error) => {
console.error(error);
});
Other packages similar to @microsoft/microsoft-graph-client
msal
The 'msal' (Microsoft Authentication Library) package focuses on authentication and acquiring tokens for Microsoft services. While it does not provide direct access to Microsoft Graph endpoints, it is often used in conjunction with @microsoft/microsoft-graph-client to handle authentication.
node-outlook
The 'node-outlook' package is designed specifically for interacting with Outlook services. It provides functionalities for accessing mail, calendar, and contacts, similar to what @microsoft/microsoft-graph-client offers but is more focused on Outlook.
Microsoft Graph JavaScript Client Library
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 v1.0 and beta!!
Node version requirement
Node.js 12 LTS or higher. The active Long Term Service (LTS) version of Node.js is used for on-going testing of existing and upcoming product features.
For Node.js 18 users, it is recommended to disable the experimental fetch
feature by supplying the --no-experimental-fetch
command-line flag while using the Microsoft Graph JavaScript client library.
Installation
Via npm
npm install @microsoft/microsoft-graph-client
import @microsoft/microsoft-graph-client
into your module.
Also, you will need to import any fetch polyfill which suits your requirements. Following are some fetch polyfills -
import "isomorphic-fetch";
import { Client } from "@microsoft/microsoft-graph-client";
Via Script Tag
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.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/whatwg-fetch/dist/fetch.umd.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@babel/polyfill@7.4.4/dist/polyfill.min.js"></script>
Getting started
1. Register your application
To call Microsoft Graph, your app must acquire an access token from the Microsoft identity platform. Learn more about this -
2. Create a Client Instance
The Microsoft Graph client is designed to make it simple to make calls to Microsoft Graph. You can use a single client instance for the lifetime of the application.
For information on how to create a client instance, see Creating Client Instance
3. Make requests to the graph
Once you have authentication setup and an instance of Client, you can begin to make calls to the service. All requests should start with client.api(path)
and end with an action.
Example of getting user details:
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
Example of sending an email to the recipients:
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.
Samples and tutorials
Step-by-step training exercises that guide you through creating a basic application that accesses data via the Microsoft Graph:
The Microsoft Graph JavaScript SDK provides a TokenCredentialAuthenticationProvider
to authenticate using the @azure/identity
auth library. Learn more:
The Microsoft Graph JavaScript SDK provides a LargeFileUploadTask
to upload large files to OneDrive, Outlook and Print API:
Questions and comments
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.
Contributing
Please see the contributing guidelines.
Additional resources
Tips and Tricks
Third Party Notices
See Third Party Notices for information on the packages that are included in the package.json
Security Reporting
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.
License
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");
We Value and Adhere to the Microsoft Open Source Code of Conduct
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.