Back

Step by Step Guide to Building a Microsoft Graph API Integration in C#

Aug 7, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Microsoft Graph API? If you're looking to supercharge your C# applications with access to Microsoft 365 data, you're in the right place. We'll be using the Microsoft.Graph package to make our lives easier, so buckle up and let's get started!

Prerequisites

Before we jump in, make sure you've got these essentials:

  • .NET SDK (latest stable version)
  • Visual Studio or your IDE of choice
  • An Azure AD app registration (don't worry, it's quick and painless)

Got all that? Great! Let's move on to the fun stuff.

Setting up the project

First things first, let's create a new C# project. Fire up your IDE and create a new console application. Now, let's add some Graph goodness to our project:

dotnet add package Microsoft.Graph

Easy peasy, right?

Authentication

Alright, time to tackle authentication. We'll be using MSAL.NET to handle this for us. Add the Microsoft.Identity.Client package to your project:

dotnet add package Microsoft.Identity.Client

Now, let's acquire an access token:

var scopes = new[] { "User.Read" }; var clientId = "YOUR_CLIENT_ID"; var tenantId = "YOUR_TENANT_ID"; var app = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .WithRedirectUri("http://localhost") .Build(); var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); var accessToken = result.AccessToken;

Initializing GraphServiceClient

With our access token in hand, let's create a GraphServiceClient:

var graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); }));

Making API calls

Now for the good stuff - let's make some API calls!

GET request

var user = await graphClient.Me.Request().GetAsync(); Console.WriteLine($"Hello, {user.DisplayName}!");

POST request

var newEvent = new Event { Subject = "Team lunch", Start = new DateTimeTimeZone { DateTime = "2023-06-15T12:00:00", TimeZone = "Pacific Standard Time" }, End = new DateTimeTimeZone { DateTime = "2023-06-15T13:00:00", TimeZone = "Pacific Standard Time" } }; await graphClient.Me.Events.Request().AddAsync(newEvent);

Handling pagination

var messages = await graphClient.Me.Messages .Request() .Top(10) .GetAsync(); while (messages.NextPageRequest != null) { messages = await messages.NextPageRequest.GetAsync(); // Process messages }

Working with specific Graph API endpoints

The Graph API is vast, but here are some common endpoints you might find useful:

Users

var users = await graphClient.Users.Request().GetAsync();

Groups

var groups = await graphClient.Groups.Request().GetAsync();

Calendar events

var events = await graphClient.Me.Calendar.Events.Request().GetAsync();

OneDrive files

var driveItems = await graphClient.Me.Drive.Root.Children.Request().GetAsync();

Error handling and best practices

Always implement retry logic for transient errors:

var retryHandler = new RetryHandler(new HttpClientHandler(), 3); var httpClient = new HttpClient(retryHandler); var graphClient = new GraphServiceClient(httpClient, ...);

And don't forget to handle common errors gracefully:

try { // Your Graph API call here } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.TooManyRequests) { // Handle throttling } // Handle other exceptions }

Conclusion

And there you have it! You're now equipped to integrate Microsoft Graph API into your C# applications. Remember, this is just scratching the surface - there's so much more you can do with Graph API.

Keep exploring, keep coding, and most importantly, have fun! If you want to dive deeper, check out the official Microsoft Graph documentation and sample repos on GitHub. Happy coding!