GithubHelp home page GithubHelp logo

isabella232 / msgraph-sdk-javascript Goto Github PK

View Code? Open in Web Editor NEW

This project forked from microsoftgraph/msgraph-sdk-javascript

0.0 0.0 0.0 8.1 MB

Microsoft Graph client library for JavaScript

Home Page: https://graph.microsoft.com

License: MIT License

TypeScript 95.03% HTML 0.10% PowerShell 4.86%

msgraph-sdk-javascript's Introduction

Microsoft Graph JavaScript Client Library

npm version badge Travis Known Vulnerabilities Licence code style: prettier Downloads

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!

TypeScript demo

Installation

Via npm

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";

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.

<!-- 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/[email protected]/dist/polyfill.min.js"></script>

Getting started

1. Register your application

Register your application to use Microsoft Graph API using one of the following supported authentication portals:

2. Authenticate for the Microsoft Graph service

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.

Creating an instance of ImplicitMSALAuthenticationProvider in browser environment

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);

Creating an instance of ImplicitMSALAuthenticationProvider in node environment

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.

3. Initialize a Microsoft Graph Client object with an 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.

For browser environment

const options = {
	authProvider, // An instance created from previous step
};
const Client = MicrosoftGraph.Client;
const client = Client.initWithMiddleware(options);

For node environment

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.

4. 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 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.

Documentation

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

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 [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.

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 [email protected] with any additional questions or comments.

msgraph-sdk-javascript's People

Contributors

abrax20 avatar baywet avatar behnammodi avatar blueboxes avatar bullsseye avatar casieber avatar dan-silver avatar darrelmiller avatar ddyett avatar dependabot[bot] avatar dingenis avatar dpim avatar gidsg avatar hasridha avatar iogi avatar kevintcoughlin avatar krototype avatar lewgordon avatar mattdenkers avatar michaelmainer avatar muthurathinam avatar nakawankuma avatar nikithauc avatar nmetulev avatar officeglobal avatar oliviercuyp avatar scriby avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.