Menu Close

Make a Microsoft graph call using javascript

To make a Microsoft Graph call in JavaScript, you will need to use the Microsoft Graph JavaScript Client Library. This library allows you to make HTTP requests to the Microsoft Graph API and handle the responses.

First, you will need to install the library using npm:

npm install @microsoft/microsoft-graph-client

Once the library is installed, you can use it to make a Microsoft Graph call in your JavaScript code. Here is an example of how to use the library to make a GET request to the /me endpoint, which returns information about the authenticated user:

const graph = require('@microsoft/microsoft-graph-client');

// Set the client_id and client_secret of your app
const client_id = 'YOUR_APP_CLIENT_ID';
const client_secret = 'YOUR_APP_CLIENT_SECRET';

// Set the redirect_uri of your app
const redirect_uri = 'https://localhost:3000/redirect';

// Set the scopes that your app requires
const scopes = [
  'user.read',
  'calendars.read'
];

// Initialize the Microsoft Graph client
const client = graph.Client.init({
  authProvider: (done) => {
    // Initialize the OAuth2 client
    const oauth2 = graph.Oauth2Client.init({
      clientId: client_id,
      clientSecret: client_secret,
      redirectUri: redirect_uri
    });

    // Get the user's access token
    oauth2.getAccessToken(scopes)
      .then((accessToken) => {
        done(null, accessToken);
      })
      .catch((err) => {
        done(err, null);
      });
  }
});

// Make the GET request to the /me endpoint
client.api('/me')
  .get()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error(err);
  });

This code will initialize the Microsoft Graph client and use it to make a GET request to the /me endpoint. The response from the API will be logged to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *