When so many apps and services are available, there is a huge need for proper APIs to access those services. But I have to say, Microsoft has done a mediocre job of providing APIs.

I had to use the OneNote API for my app “Action Toasts“. So, I started searching for it. All my searches went to the age old Live SDK. After reading its documentation, I came to know that it is not available any more and I should shift to the new OneDrive SDK. But on reading OneDrive SDK, it told me that Microsoft Graph API is the present way to get it done. But actually all the three APIs work.

Now that I have settled with Graph API, I went ahead to search for prebuild libraries. That’s how I found this – Microsoft Graph Client Library for .Net, the official library for Graph API. But the problem with using this is SDK is that it is implemented as a general .Net library. So, it does not have the luxury of features UWP has. For example, it has to use the standard OAuth to authenticate the users access, while for UWP, all you have to do is to choose your Microsoft account from the list shown and it’s done!

So, let’s see how to consume Graph API properly.

Prerequsites

Register your app in Microsoft Application Developer Portal Get your client ID/App ID. If you have registered your app in the Windows Store, a client ID will be waiting for you before you arrive.

Authentication

Graph SDK would suggests you to use the Azure Active Directory Library (AADL). AADL uses OAuth to authenticate. Since the library is meant to be cross-platform, it is acceptible. Don’t you think it would be an insult to ask for your Microsoft Account password when you are on a platform that completely runs on it? So, we have a better way to do it!

Use WebAccountManager Microsoft has a good documentation on it. Follow the documentation till the point where it explains how to use Graph API to signin. The list of scopes are present in Graph API documentation under their topics The WebTokenRequestResult contains the token to access the API Store the token in the local settings for future use.

WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { string token = result.ResponseData[0].Token; }

Refreshing the token

The Graph API token expires after sometime. Then, you have to refresh it for a new token. AADL does it for you. But if you are going to use the above said method, you have to do it on your own.

On getting your token, a TokenExpiresOn field, along with many others, is also sent. You can get it by accessing your result.ResponseData[] . This StackOverflow answer tells you how to get the Expiration Time. Track the token expiration. Once it expires, use WebAuthenticationCoreManager.GetTokenSilentlyAsync() to get the new token

var provider = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers"); WebTokenRequest request = new WebTokenRequest(provider, "User.Read Notes.Create", clientId); request.Properties.Add("resource", "https://graph.microsoft.com"); WebTokenRequestResult result; result = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(request); if (result.ResponseStatus == WebTokenRequestStatus.Success) { accessToken = result.ResponseData[0].Token; }

Or if you feel too lazy to keep track of the expiration time, you can always call the WebAuthenticationCoreManager.GetTokenSilentlyAsync() before each time you want to use the Graph API. You will get the same token back if it hasn’t expired or you will get the refreshed token.

Consuming the API

From this point, you can follow the Graph SDK docs. Provide the accessToken to the DelegateAuthenticationProvider as mentioned here

The Graph SDK uses System.Net.Http instead of Windows.Web.Http . If you are fine with it, no problem. But if you want to take full advantage of the new Windows.Web.Http , follow here.

Create a new HttpClient object. Add the authentication headers to it. The accessToken is the one you received before. Use this client to make further API calls. Refer the Graph API documentation when required. As an example, I have implemented the OneNote API.

HttpClient client = new HttpClient; client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", accessToken);

string requestUrl = "https://graph.microsoft.com/v1.0/me/onenote/pages/"; string htmlBody = @"OneNoteAddPageHtml created thisGenerated with love"; HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, new Uri(requestUrl)) { Content = new HttpStringContent(htmlBody, Windows.Storage.Streams.UnicodeEncoding.Utf8, "text/html") }; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", settings.MsaAccessCode); var response = await client.SendRequestAsync(msg); if(response.IsSuccessStatusCode) return SimpleNotif("OneNote Action", "Your note has been sent to OneNote"); else return SimpleNotif("OneNote Action", "An error occured");

And that’s it! Happy Coding!