Building Go applications with the Microsoft Graph Go SDK, now generally available

Maisa Rissi

Have you ever wanted to access Microsoft data and services in your Go applications? Now you can, with the Microsoft Graph Go SDK, now generally available.

The Microsoft Graph Go SDK is a client library that lets you connect and retrieve data from any of the supported Microsoft services that are available on Microsoft Graph API and provide to users many features that will increase resiliency, better performance, ease authentication and more.

The client library is generated using Kiota, a new code generator that is now generally available and enables us to provide a consistent and fluent API across different platforms. Today we will show you how to use the Microsoft Graph Go SDK to integrate your applications with Microsoft Graph and leverage some of the features that can make your development easier and more efficient.

Authenticate easily in various scenarios

Depending on your application type and scenario, you may need different ways to authenticate to Microsoft Graph and get access tokens. As an example, you should consider client credentials auth flow when you want to authenticate your application without any user interaction. This scenario is suitable for daemon apps or background services that run on servers or devices. Or when you want to authenticate your application with a certificate instead of a secret, for confidential client applications that need a higher level of security, you can take advantage of certificate credentials.

The Microsoft Graph Go SDK supports various authentication scenarios to allow you succeed in any scenario you might have by taking advantage of the Azure Identity library. You don’t need to worry about the complexity of acquiring tokens from Azure Active Directory (AAD), because the SDK uses the Azure Identity library for Go to handle that for you. The Azure Identity library provides a set of credential classes that are compatible with the Microsoft Graph Go SDK and can authenticate requests to Microsoft Graph.

So, if you want to use the device code flow, which is ideal for devices that have limited input capabilities like IoT devices, TVs, and wearables, you can simply use the DeviceCodeCredential class and provide your client ID and tenant ID. Then you can use the credential to create a GraphServiceClient instance and call the Microsoft Graph API, as the following code:

Access latest features and APIs available in Microsoft Graph API

Users should always rely on Microsoft Graph v1.0 when building their application for production environments. However, sometimes there is a need to use the Microsoft Graph beta endpoint for testing or early adoption before a feature is available in v1.0. The beta endpoint and the functionalities there are still in preview status, can change or introduce breaking changes at any point in time. This makes the beta endpoints unreliable for production usage since it may break existing scenarios without notice.

For you to be able to access the latest features and APIs that are in preview on Microsoft Graph, the Microsoft Graph Go SDK has a companion beta SDK. The beta SDK is generated from the beta metadata and follows the same API design and conventions as the v1.0 SDK. You can use both SDKs in the same project, but you need to import them with different aliases to avoid name conflicts.

For example, to create a v1.0 client and a beta client with the same credential, you can use the following code:

Write readable code with fluent API style

With the fluent API style, you can write code that is clear, concise, and expressive. You can also avoid errors and typos by using the auto-completion feature of your IDE. The fluent API style makes your code easier to maintain and debug. You can chain methods and properties to build requests and access resources in a consistent way. The fluent API style matches the Microsoft Graph REST API syntax and makes it simple to switch between the SDK and raw HTTP requests.

For example, to get the messages in the inbox folder of the signed-in user, you can use the following code:

To create a new message and send it to a recipient, you can use the following code:

Iterate large collections of data

One of the challenges of working with large collections of data is that they can be too big to fit in a single response. For example, if you want to get all the messages in a user’s mailbox, you might have to make multiple requests to the Microsoft Graph API and concatenate the results. This can be tedious and inefficient.

You can use the Microsoft Graph Go SDK to have a convenient way to handle pagination. PageIterator simplifies consuming paged collections by enumerating the current page and requesting subsequent pages automatically. You can use it to iterate over all the items in a collection without worrying about the details of pagination.

For example, to get all the messages in the inbox folder of the signed-in user, you can use the following code:

You can pause and resume the iteration process by returning false from the callback function and calling the Resume method. This can be useful for scenarios where you need to perform other actions between iterations.

Using pagination with the Microsoft Graph Go SDK can help you access large collections of data more easily and efficiently. You can use it to get all the data you need with less code and fewer requests. To learn more about pagination with the Microsoft Graph Go SDK, check out this article.

Perform multiple tasks with improved performance

With the Microsoft Graph Go SDK, you can perform multiple tasks with one batch request. A batch request lets you combine multiple requests into one, which can improve the performance and efficiency of your application by reducing the number of network round trips.

With batch requests, you have the flexibility to include different types of requests, such as GET, POST, PATCH, or DELETE, and access different resources, such as users, groups, events, to cover the most diverse scenarios your business might need. In addition, you have the option to specify dependencies between tasks, so that one task can be executed after another task is completed. Moreover, you have the convenience to handle errors more easily, as you can identify which request failed and why by using the id and status properties in the batch response.

To create a batch request, you only need to create a NewBatchRequest and provide a slice of BatchRequestStep objects. Each BatchRequestStep object represents a single task within the batch and has a unique ID. You can also specify dependencies between tasks, so that one task can be executed after another task is completed. For example, if you want to create a batch request that contains three tasks: get your profile, get your profile photo, and update your display name that depends on getting your profile first, you can simply use the DependsOnItem method and add the dependency tasks to it. Then you can execute the batch request and process the batch response as shown in the following code:

Sometimes, you may need to perform batch requests on large collections of items, such as messages, events, or users. However, the Microsoft Graph API has a limit of 20 requests per batch. To overcome this limitation, you can use the BatchCollection class in the Microsoft Graph Go SDK. The BatchCollection class allows you to create batch requests with more than 20 items by splitting them into smaller batches and executing them sequentially. You can also specify a callback function to handle the responses of each batch.

For example, if you want to delete 100 messages from your inbox folder, you can use the BatchCollection class like this:

Save bandwidth and improve performance

Another challenge of working with data from the Microsoft Graph API is that you might want to update only the properties that have changed, instead of sending the whole entity back to the server. For example, if you want to update the display name of a user, you don’t need to send all the other properties of the user that have not changed. This can save bandwidth and improve performance.

That’s why the Microsoft Graph Go SDK provides a feature called backing store and dirty tracking. The backing store is a map that stores the original values of the properties of an entity. The dirty tracking is a mechanism that tracks which properties have been modified since they were fetched from the server. These features allow you to update only the changed properties rather than the entire entity.

The backing store and dirty tracking can help you update data more efficiently and selectively. You can use it to send only the changes you need with less code and fewer bytes. To learn more about backing store and dirty tracking, check out this documentation.

Create a smaller and tailored Microsoft Graph Go client library

Size is often a concern for developers. One of the benefits of using Kiota is that you can customize your client library to include only the endpoints and APIs that you care about. This can improve the performance and size of your application by reducing the amount of code and dependencies.

To generate a custom library for Microsoft Graph using Kiota, you can opt for the CLI experience or the Visual Studio Code extension.

Whichever experience you choose, you will be able to search for the Microsoft Graph openAPI description, include and exclude the paths you’re interested in and finally generate.

You can also use the resources explorer feature on Graph Explorer to select the endpoints you need and download the metadata file and use it as an input to the CLI command and generate your client.

For example, one way to generate a custom client library that includes only the /me endpoint and its related entities, after having Kiota installed, is to use the following command:

kiota generate --openapi --language go --output path\to\sdk\microsoft-graph-go-kiota\client --class-name GraphBaseServiceClient --namespace-name microsoft-graph-go-kiota\client --backing-store --include-path '/me'

Note: Visit Kiota client generation to discover all parameters supported

Note 2: The –include-path parameter is how you can limit what APIs will be supported by the client library including just the paths that you are interested in. You can add the parameter –include-path multiple times to include multiple path glob patterns.

The above command will generate a Go module in the output folder that contains only the code for accessing the /me endpoint. You can then use this module in your application and add the Microsoft Graph Go Core library as a dependency to get all the middleware and common tasks. To do that, go to the output root folder, in this case path\to\sdk\microsoft-graph-go-kiota and run:

go mod init microsoft-graph-go-kiota

go mod tidy

go get

go get

And for the above client, you can now access any Microsoft Graph /me endpoints as if you had the entire Microsoft Graph Go client installed.

For more information about Kiota, see the documentation.

Try out the new version today!

We are excited about the Microsoft Graph Go SDK. We encourage you to try out the new version and let us know what you think on GitHub! For questions about the Microsoft Graph API, go to Microsoft Q&A.

Learn more about Microsoft Graph SDKs

The SDK includes a set of tools, libraries, and documentation that make it easy to get started building applications that take advantage of the rich data and insights available through Microsoft Graph API.

Start saving time and removing complexity in your code today. Sign up for the Microsoft 365 Developer Program to get a free Microsoft 365 developer subscription and start using Go to connect to Microsoft Graph. We also recommend that you join our Microsoft 365 Platform community calls and events and get involved with other developers who use Microsoft Graph and build solutions for Microsoft 365.

Here are some resources we have pulled together to help you get started.

Thank you!

We would like to thank all the members of the community who have helped us make this release better by reporting issues in GitHub! Keep them coming!


Discussion is closed.

Feedback usabilla icon