Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
@microsoft/microsoft-graph-client
Advanced tools
@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.
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);
});
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.
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.
The Microsoft Graph JavaScript client library is a lightweight wrapper around the Microsoft Graph API that supports both Node and the browser. See the samples folder for code examples. You can also use our TypeScript graph types with this library.
This client library is currently in preview and we would love to hear your feedback! You can file an issue in this repository or write on our uservoice page. We're also trying to add more intellisense support beyond the current typings so we're also especially interested in feedback on the Microsoft Graph TypeScript Typings.
You can find installation instructions at the Node.js website.
npm install @microsoft/microsoft-graph-client
Include the library in your JavaScript file with const MicrosoftGraph = require("@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>
graph-js-sdk-web.js
for web apps3.3.0
MicrosoftGraph.Client.init({...})
. See the updated usage section below for code samples.This client library only handles authentication in the most basic way possible. The application is responsible for refreshing tokens and returning an immediately valid access token in the authentication provider.
var client = MicrosoftGraph.Client.init({
authProvider: (done) => {
done(null, "PassInAccessTokenHere"); //first parameter takes an error if you can't get an access token
}
});
All calls to Microsoft Graph are chained together starting with client.api(path)
. Path supports the following formats:
For more examples of accepted paths, see the test cases.
// Example calling /me with no parameters
client
.api('/me')
.get((err, res) => {
console.log(res); // prints info about authenticated user
});
Calls should start with .api()
, then chain query parameters and end with an action.
// get the names of my top 5 contacts on the beta endpoint
client
.api('me/people')
.version("beta") //optional, but recommeded to have before query params
.top(5)
.select("displayName")
.get((err, res) => {
const topContacts = res.value.map((u) => {return u.displayName});
console.log("Your top contacts are", topContacts.join(", "));
});
The actions(.get(), .put(), etc.) accept a callback or don't pass in a function to get back a Promise.
client
.api('/me')
.select("displayName")
.get()
.then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
The first parameter of .post()
and .patch()
takes an object that will be sent as the content of the request.
// construct the 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"
}
}
client
.api('/users/me/sendMail')
.post({message: mail}, (err, res) => {
console.log(res)
})
.del()
and .delete()
// delete a OneDrive item
client
.api(`/me/drive/items/${ONE_DRIVE_FILE_ID_TO_DELETE}`)
.delete((err, res) => {
if (err) {
console.log(err)
return;
}
console.log(res)
})
.put()
and .putStream()
You can upload files to the graph using .put()
. For example, this can be used to update a profile picture from an HTML input form. See the browser sample for complete code.
var file = document.querySelector('input[type=file]').files[0];
client
.api('/me/photo/$value')
.put(file, (err, res) => {
if (err) {
console.log(err);
return;
}
console.log("We've updated your picture!");
});
Use .putStream()
to upload files to Microsoft Graph with Node.js streams.
// Upload a file to OneDrive
let fs = require('fs'); // requires filesystem module
let stream = fs.createReadStream('./logo.png'); //path to local file
client
.api('/me/drive/root/children/logo.png/content') // path to the destination in OneDrive
.put(stream, (err) => {
console.log(err);
});
.getStream()
Use .getStream()
to stream a download from Microsoft Graph.
const fs = require('fs'); // requires filesystem module
client
.api('/me/drive/root/children/Book.xlsx/content') // path of source file in OneDrive
.getStream((err, downloadStream) => {
let writeStream = fs.createWriteStream('Book.xlsx'); // path to save file to
downloadStream.pipe(writeStream).on('error', console.log);
});
These methods can take a string property, an array of strings or you can pass in each value as a separate argument.
.select("birthday")
.select("department")
// same as
.select("birthday", "department")
// same as
.select(["birthday", "department"])
client
.api('/me/people')
.select(["displayName", "department", "title"])
.get((err, res) => {
console.log(res)
})
These parameters only take a number. Calling them multiple times is not supported.
.top(5)
.skip(10)
Set .count() to true to also return the number of objects in the collection.
.count(true)
Pass a filter string to .filter()
for filtering result collections. Calling filter multiple times will override previous filter strings.
client
.api("/users")
.filter("startswith(displayName, 'david')")
.get((err, res) => {
console.log(res)
})
Passing in a version through .version()
has the highest priority. It overrides the Microsoft Graph client default version from .init()
and the global library default (currently v1.0).
You can pass in any URL query parameters as a dictionary or string.
.query({"$select":"displayName"})
// same as
.query("$select=displayName")
// same as
.select("displayName")
You can pass in additional request headers, either individually or in a dictionary.
.header("someHeaderName", "someHeaderValue")
// or
.headers({"someHeaderName":"someHeaderValue"})
To set a custom response type, use the .responseType(string)
method. To see an example, check the browser sample that downloads an image and displays it in an <img>
element.
MicrosoftGraph.Client.init()
The following are optional parameters to pass to MicrosoftGraph.Client.init(), except for the authProvider:
The full response containing the headers, status code, and body can be obtained by passing a third parameter to the callback.
client
.api('/me')
.select("displayName")
.get((err, res, rawResponse) => {
console.log(rawResponse.statusCode);
console.log(rawResponse.header);
});
var date = new Date();
date.setDate(date.getDate()-365); // ~ 1 year ago
client
.api('/me')
.body({"birthday": date})
.update((err, res) => {
console.log("Updated my birthday")
})
These steps are not required to use this library.
npm install
installs development dependencies (TypeScript, Mocha, etc.).
Note: If you want to run
tsc
from the command line, install TypeScript globally withnpm install -g typescript
or reference./node_modules/.bin/tsc
npm run build
generates lib/ files for node and browser versions.
npm pack
bundles the npm module.
npm test
runs tests.
To build only browser version:
node node-browserify.js > lib/graph-js-sdk-web.js
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.
Copyright (c) 2016 Microsoft. All rights reserved.
0.4.0
graph-js-sdk-web.js
for web appsFAQs
Microsoft Graph Client Library
The npm package @microsoft/microsoft-graph-client receives a total of 339,969 weekly downloads. As such, @microsoft/microsoft-graph-client popularity was classified as popular.
We found that @microsoft/microsoft-graph-client demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.