The Microsoft Graph API is a service provided by Microsoft that allows developers to connect their applications to Microsoft cloud services such as (Sharepoint, OneDrive, Mail, Calendar, Active Directory etc).

https://developer.microsoft.com/en-us/graph

It took me a little while to understand and figure out how to integrate the Graph API into our own internal API services. To help you out, this article shows how I accomplished authentication and how i consumed some of the Graph API services within my own internal API services.

Ok let’s get started!

Setting Up

As the integration stems from an internal API, I needed to grant access to the Graph API without user credentials. Reason being, is that my internal API acts as a service. So I wasn’t interested in executing Graph commands as a user.

This article details the steps on how to perform the following:

https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service

1. Registering your app with Azure AD
2. Saving the Secret keys for authentication
3. Requesting the necessary permissions for the app in order for it to call the relevant Graph API functions
4. Getting an Azure administrator to approve the request for permissions.

Example

The example I will use will be calling the Graph APIs “UpdateMailBoxSettings” function to set an account automatic reply settings.

https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_update_mailboxsettings

Let’s jump right into the code:

        [HttpPost]
        public async Task<Entity.UpdateMailboxResponse> UpdateMailboxSettings([FromBody]Entity.UpdateMailboxRequestData RequestData)
        {
            string accessToken = await this.GetToken();
            string endpoint = "https://graph.microsoft.com/v1.0/users/" + RequestData.Email + "/mailboxsettings";

            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), endpoint))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    Entity.MSGraph_UpdateMailboxRequest body = new Entity.MSGraph_UpdateMailboxRequest();
                    body.automaticRepliesSetting = new Entity.MSGraph_automaticRepliesSetting();
                    body.automaticRepliesSetting.scheduledStartDateTime = new Entity.MSGraph_DateType() { dateTime = RequestData.StartDate.ToUniversalTime(), timeZone = "UTC" };
                    body.automaticRepliesSetting.scheduledEndDateTime = new Entity.MSGraph_DateType() { dateTime = RequestData.StartDate.AddYears(5).ToUniversalTime(), timeZone = "UTC" };
                    body.automaticRepliesSetting.status = "Scheduled";
                    body.automaticRepliesSetting.internalReplyMessage = RequestData.Message;
                    body.automaticRepliesSetting.externalReplyMessage = RequestData.Message;
                    body.automaticRepliesSetting.externalAudience = "all";


                    request.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");

                    using (var response = await client.SendAsync(request))
                    {
                        var resp = new Entity.UpdateMailboxResponse();

                        if (response.IsSuccessStatusCode)
                        {
                            resp.SetEsError(new Entity.EsError("S", response.ReasonPhrase));
                        }
                        else
                        {
                            resp.SetEsError(new Entity.EsError("E", response.ReasonPhrase));
                        }
                        return resp;
                    }
                }
            }
        }

The first step is to obtain an Access Token. This token is submitted with your request to authenticate who you are with the Graph API.

        private async Task<string> GetToken()
        {
            using (var client = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod("POST"), MSGraph_APIURL))
                {
                    string body = @"client_id=" + MSGraph_AppId;
                    body += @"&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default";
                    body += @"&client_secret=" + MSGraph_Secret;
                    body += @"&grant_type=client_credentials";

                    request.Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

                    using (var response = await client.SendAsync(request))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var json = JObject.Parse(await response.Content.ReadAsStringAsync());
                            return json.GetValue("access_token").ToString();
                        }
                        return string.Empty;
                    }
                }
            }

        }

Below are the configurations you will need to save in your app/web.config files. These values would come from the Setup section where you registered your Azure AD app.

    <add key="MSGraph_APIURL" value="https://login.microsoftonline.com/[[tenant name]]/oauth2/v2.0/token"/>
    <add key="MSGraph_AppId" value="[[your app id]]"/>
    <add key="MSGraph_Secret" value="[[your secrete key]"/>

After all of this, the second step in this function is to create a HTTP client to post our request. Make sure you use the correct HTTP METHOD — in this case we need to use the PATCH method.

In the Request Header, pass in the access token.

Set the necessary parameters for the Graph API function.

Send the request!

If all went well, your response would be HTTP 200; and if the call returns data, you can evaluate this using the response object.

That’s it! It does look very simple. But trust me, it took me a while to figure out how to get the correct Access Token. But once that was working, calling any Graph API is relatively straight forward. You can even follow this template code, and replace it with other Graph API calls.

Hope this helped!