Observations on the Microsoft Graph SDK for Python
Image generated with Copilot AI

Observations on the Microsoft Graph SDK for Python

Over the last several months, my colleague Mike Robinson and I have been slowly working on an internal passion project which required accessing data inside our Microsoft 365 tenant. We decided that Python would be our language of choice and after a quick evaluation of existing libraries, we determined that Microsoft’s Graph SDK (Software Development Kit) for Python was right to address all the features we wanted. Mike and I have been close collaborators for a while and when one of us got stuck, we fell back to a familiar pattern of getting together for a quick meeting to lend personal experience and different perspectives to get unstuck. Over a number of these calls, we both found that using this library was a slightly different experience than other libraries we’ve onboarded in the past. We hope that by sharing our observations it can help others move faster in adopting a Microsoft Graph SDK for their needs.

Microsoft Graph

If you’re unfamiliar with Microsoft Graph, it is the entry point to data for all things Microsoft 365.? Graph supplies a single endpoint exposing REST APIs to Microsoft’s cloud services. Familiar products such as Excel, OneDrive, Outlook/Exchange, and Teams are among the large list of services that can be accessed via the Graph API. ?Additionally having a single API that spans so many products can really reduce the complexity of building applications for a developer. ?

Authentication with the Microsoft Graph API

Mike Robinson

Within the Python SDK for MS Graph, there is a simple GraphServiceClient that needs to be initialized to make requests to the API. ?The SDK makes it easy to manage authentication, however, it is important to understand the architecture involved in that process and what it takes to get to the service client step.

Application Registration

Before using the Microsoft Graph API, you need to register an application in the Azure AD Applications section within “App Registrations”. This registration process generates a client ID and secret (otherwise known as an application password) and allows you to configure API Permissions (either delegated or application permissions as discussed in the next section).? The client ID and secret are used to request an access token within the SDK.

Permissions

To access specific resources in the Graph API, the application registered in Azure AD needs appropriate permissions.? The permissions needed depend upon the type of integration in use, such as “Calendar Read” access is needed if the application reads user’s calendar data.?

API Permissions can be 1 of 2 types:

  • Delegated – this type involves having the Graph API perform tasks on behalf of a user.? For example, if the application is geared toward users and reading their emails, the user will first grant the application access by signing into Microsoft via OAuth (Open Authorization).
  • Application – this type is not tied to any user and might read or write data for multiple users.? Most application permissions require access to be granted by an Azure administrator.? An example of application permissions is an application that reads all user calendars and provides metrics regarding daily white space.

Permissions are granted either by the user (“User Consent” must be enabled on the tenant) in delegated types, or by an administrator during the application registration process for application types.

Access and Refresh Tokens

After successful authentication, the Graph API issues an access token back to the application using the SDK. This token is used to authenticate requests to the API on behalf of the user or the application.

Access tokens have a short expiration time and after expiration, require getting a new one via a refresh token (which has a longer life span).? An application needs to handle token expiration by getting a new one, or if the refresh token is expired, by re-authenticating the user.

For more information about Microsoft Graph API security, see this Microsoft article: Authentication and authorization basics.

Luckily, the SDK takes care of the token refresh process by using what is called the Microsoft Authentication Library (or MSAL).? Instead of manually having to check for token expiration, the MSAL within the SDK will automatically determine if the access token is about to expire, and if so, request a new one and store it in a token cache.? See the Microsoft article “Overview of the Microsoft Authentication Library (MSAL)” to view features in greater detail if interested.

Builder Pattern

Colin Vallance

Unlike several other SDKs I’ve used for REST APIs in the past, the Graph SDK seems to utilize a builder pattern for its client instead of crafting a payload. If you’re not familiar, the builder design pattern is a creational pattern that lets developers build up complex objects in stages. This can be very useful if code needs to use different representations of that complex object and rather than trying to create a giant constructor with lots of anticipated values. I’ve found this pattern particularly useful for tests when I need to pass in a variety of options and want to try each possibility. ?A simple example is shown below (Figure 1.) along with the output (Figure 2.).

Figure 1.
Figure 2.

You can see in the first demo all the default values are displayed but in the second and third examples, individual elements are changed using a builder pattern that updates the existing default values for the instance. Using meaningful names for the class methods makes the intent of this pattern very clear for the end user.

Relating this back to the Python SDK, if we look at the “list replies” Graph endpoint in Figure 3. as an example, we can see that this call requires a team id, a channel id, and a message id to return the requested data.

Figure 3.

The provided implementation example in Python, seen in Figure 4., shows how the SDK expects the usage of a builder instead of manually manipulating the URL or supplying a payload that holds the desired data. This is a perfectly reasonable way to approach making these calls but might be confusing if you’ve never seen this before and might not be as intuitive as adjusting a URL. ??

Figure 4.

API Exploration

Colin Vallance

When I approach a new API or SDK there are a couple of things that I always try to lay out in front of myself to maximize my success. First and foremost, documentation is crucial to understand what can be done, what perhaps can’t be done, and how to properly implement your code. Secondarily having the right toolset as you explore is important as it can help sanity check operations and speed up evaluation. ?

Documentation

Microsoft has extensive documentation on Graph with a whole landing page that can help direct you towards the information you may need. ?The REST API endpoint reference is very dense but contains common use cases, and endpoint details that will allow you to understand it’s capabilities and how to make calls. One other useful part of the reference site which is easy to miss is the version choice. While v1.0 is the stable version as of the time this is being written, there is a beta version available which is worth reviewing if you find that one of your needs isn’t met with existing endpoints. While the request example sections have the possibility to show syntax for a language of your choice, this is often not enough to understand how to use the SDK for that language. I often found myself looking at the documentation included with the Python SDK’s code on GitHub or even the code itself when my code using builder patterns were failing. In the end knowing that developer docs are not the only source of information and being willing to search for other sources can get you pretty far.

Tools

Often tools go hand in hand with documentation when trying to pick up an SDK. Microsoft provides a fantastic tool called Graph Explorer that rolls up all the things we’re already outlined as necessary. You can select different endpoints and have an example URL populated, choose between v1.0 and the beta endpoints, generate access tokens, modify permissions as needed, and more. We returned to this tool often when things weren’t working as we expected, or we needed to quickly see query response data. More than anything else a tool like this from the provider can function as a sanity check when you can see call results even if your code isn’t working quite as expected yet. We’re lucky to have graph explorer in this case but that doesn’t mean other tools can’t help with this as well. I use Postman or even curl regularly to put together simple REST calls that can prove the logic in my code is the problem, not the API itself.

Adoption

Implementing a Microsoft Graph SDK can provide a wide range of productivity gains. For our purposes, we used the Python Graph SDK for Microsoft Teams channel management and file archiving but there are many other use cases. You could access user data for metrics, manage calendars, send emails, apply policies or retrieve device information from devices enrolled in Microsoft Endpoint Manager just to name a few.?

If you are interested in building a Graph API application, we suggest you spend some time to think about a simple use case that would help you personally. We think best way to learn a new API is to build something useful for you so consider what could be automated in your environment either at work or at home.? What you build may even be useful for others or it may inspire you to expand functionality beyond your original needs. Microsoft’s Graph GitHub site is a great resource for SDKs, sample code, and demonstrations of integrations like IFTTT from which to draw inspiration. The possibilities are endless and we hope our observations help you accelerate your Graph SDK adoption.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了