Working with the Microsoft Graph REST APIs

In this article, I will explain how to access the Microsoft Cloud services data by using the Graph REST API. Microsoft Graph exposes Cloud services data, such as Outlook mail, calendar, One Drive, tasks, groups, SharePoint, and so forth. Cloud data could be accessed from a JavaScript client application. A developer needs to set up your Office 365 development environment before accessing Cloud services.

To extract data, follow these steps:

  1. Register the application.
  2. Get an access token for authentication.
  3. Access the Microsoft services data over the Graph API.

Register Your Application

In my previous Graph article, “Reading Text from Images Using C#,” I had explained the steps to register and generate the platform-specific App ID. Access the graph apps portal once your App ID is generated.

In the app details page, provide the app name and generate new key pair; then, save the password securely. Make sure you add the appropriate platform; I have selected Web, as shown in Figure 1.

From the applications page, copy the App ID, which will be used in Rest API call operations.

Graph API Test App Registration
Figure 1: Graph API Test App Registration

Add redirect and Log out URLs (see Figure 2), but these are optional.

Graph API Redirect and Logout URL setup
Figure 2: Graph API Redirect and Logout URL setup

Under the profile section, you can add home page, service, and privacy policy URLs. You also can add a logo of your app, as shown in Figure 3.

Graph API Profile page URL setup
Figure 3: Graph API Profile page URL setup

Application Permission

After registering the app, the developer should specify the permission scopes that are appropriate to access. The Microsoft Graph permissions section gives an opportunity for the developer to allow the app access to their resources with the permission scopes defined. For more details about how to configure permissions for your app and on the consent process, please refer to the app permission URL (see Figure 4).

Microsoft Graph App Permission Section
Figure 4: Microsoft Graph App Permission Section

Get the Access Token

Tokens are issued by Azure AD to authenticate JavaScript clients. We will be getting the access of a token by using the authentication server URL with the GET method.

The following parameters are passed to get the token.

  • Client ID
  • Response type
  • Resource URL
  • Redirect URL

The following function builds the authorization URL. Access the URL in your browser by using the window.location script. The page will be redirected to the redirect URL specified.

class Token {

   get clientId() {
      return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
   }

   get replyUrl() {
      return 'https://tapaspal.sharepoint.com';
   }

   get resource() {
      return 'https://graph.microsoft.com';
   }

   get authServer() {
      return 'https://login.microsoftonline.com/
         tapaspal.sharepoint.com/oauth2/authorize?';
   }
}

function requestToken() {
   const objToken = new Token();
   var clientId = objToken.clientId ;
   var replyUrl = objToken.replyUrl;
   var resource = objToken.resource;
   var authServer = objToken.authServer;
   var responseType = 'token';

   var url = authServer +
      "response_type=" + encodeURI(responseType) + "&" +
      "client_id=" + encodeURI(clientId) + "&" +
      "resource=" + encodeURI(resource) + "&" +
      "redirect_uri=" + encodeURI(replyUrl);

   window.location = url;
}

The next step would be extracting the access token from the response URL. The token will be retrieved once the page is redirected. The following function gets called once the page loads, checks for the access token in the URL, and extracts it.

function ProcessQueryString(querystring) {
   var split = querystring.split('&');
   var results = {};

   // If there are parameters in URL, extract key/value pairs.
   for (var i = 0; i < split.length; ++i) {
      var p = split[i].split('=', 2);
      if (p.length == 1)
         results[p[0]] = "";
      else
         results[p[0]] =
            decodeURIComponent(p[1].replace(/\+/g, " "));
   }

   return results;
}
var queryStringParameters;
queryStringParameters =
   ProcessQueryString(window.location.hash.substr(1));
var token = queryStringParameters['access_token'];

Accessing Cloud Data by Using the Graph API

After app registration with Azure AD is completed, determine the correct endpoint for the resource you want to access. The access token granted an access from Azure AD. Next, you have to make an XMLHttpRequest request to the API. The following function makes the request and puts the content of the response on a DOM element with an ID equal to the results.

function FetchFilesFromO365() {
   try {
      var Url = 'https://tapaspal.sharepoint.com/
         _api/v1.0/me/files';
      var xhr = new XMLHttpRequest();
      xhr.open("GET", Url);
      xhr.setRequestHeader("Authorization", "Bearer " + token);
      xhr.onload = function () {
         if (xhr.status == 200) {
            var formattedResponse =
               JSON.stringify(JSON.parse(xhr.response),
               undefined, 2);
            document.getElementById("results").textContent =
               formattedResponse;
         } else {
            document.getElementById("results").textContent =
            "HTTP " + xhr.status + "<br>" + xhr.response;
         }
      }
      xhr.send();
   }
   catch (err) {
      document.getElementById("results").textContent =
         "Exception: " + err.message;
   }
}

Summary

In the next article, I will talk about programming devices and activities using Microsoft Graph APIs. Happy Reading.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read