Write simpler, faster code with the new Microsoft Graph Java SDK v6

Maisa Rissi

The Microsoft Graph Java 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, easy authentication and more, such as fluent API and models, retry and redirect handlers, batching requests and large file management.

Today, we’re announcing the release candidate of Microsoft Graph Java SDK version 6.0. The new version of 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 and new features to enhance your development experience.

Write readable and more accurate 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.

1. Write less error-prone code with better intellisense

Users can now add headers and any query options to customize any request by using the new requestConfiguration modifier. With the new modifier, the accuracy of the intellisense in the client library was also improved, so you’ll get to see suggestions only for methods that are actually supported by the underlying API.

2. Count support available in the request builder

With a new Count functionality, SDK users can simplify extending Graph API queries with the $count segment when supported by the API. This applies only for $count as URL segment. The $count as a query string parameter needs to use the new requestConfiguration modifier as exemplified above.

3. Meaningful and simplified method chaining

Thinking of improving both the learning curve to SDK users and discoverability of what is supported by the APIs, the need to use buildRequest() for every call is now in the past, improving the code readability by making it cleaner. In addition to that, you now have getters and setters to access and manipulate values of classes fields.

As an example, let’s look at a post request using v5.

Now, SDK users can just stick to the point and only have code that means something:

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 now the new Microsoft Graph Java SDK v6 to have a convenient way to handle pagination. The new 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 Java 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 Java SDK, check out this article.

Get specialized objects with OData cast support

OpenAPI has a way to describe which property can be used as a discriminator on an object type to determine the true type of an object, adding support for polymorphism.

Because OData cast allows downcasting the result to the right specialized type, users now have access to all properties in the response, rather than pulling those out from the AdditionalData. This can be exemplified in Microsoft Graph API by members of a group, where it can be either a User, Application, Device, Group and more.

Save bandwidth, improve performance and track properties changes

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 Java 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 and unblock scenarios like disabling recurrence on an event or removing a mobile phone from a user by setting a property to null.

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.

Perform multiple tasks with improved performance

With the Microsoft Graph Java 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.

Sometimes you 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, the new BatchRequestContentCollection class is available in the Microsoft Graph Java SDK v6. The BatchRequestContentCollection 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 an optional custom implementation of IResponseHandler as part of the GetResponseById function to handle the individual response as you wish when batching.

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

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 unpredictable 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 Java SDK has a companion beta SDK. Until now, you could use both v1.0 and beta libraries in the same project, but you needed to import them with different aliases to avoid name conflicts. With these new client libraries, you can query both v1.0 and beta APIs without requiring aliases.

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

Create a smaller and tailored Microsoft Graph Java 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.

To take advantage of a customized experience, first create a new directory for your project and then run the following command in that particular directory to initialize a Java project:

gradle init --dsl groovy --test-framework junit --type java-application --project-name meclient --package meclient 

Before compile and run the generated API client, edit the “.\app\build.gradle” to add Kiota and Microsoft Graph Java core dependencies:

You can then generate a client library and add as part of your Java application. For example, one way to generate a custom client library that includes only the /me endpoint and its related entities, after having Kiota CLI installed, is to use the following command:

kiota generate --openapi https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/openapi/v1.0/openapi.yaml --language java --output app/src/main/java/meclient/apiclient --class-name GraphBaseServiceClient --namespace-name meclient.apiclient --backing-store --include-path '/me'

Note: Kiota CLI version needs to be 1.9.0 at minimum. If you already have Kiota installed, make sure its up to date by running dotnet tool update –global Microsoft.OpenApi.Kiota.

Note 2: Visit Kiota client generation to discover all parameters supported

Note 3: 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 Java client library in the output folder that contains only the code for accessing the /me endpoint.

For the above project, you can now access Microsoft Graph /me endpoint and have the core features.

For more information about Kiota, see the documentation.

Next steps

We are excited about the Microsoft Graph Java SDK v6. 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.

Add the new client library version to your project by adding following code to your dependencies:

MAVEN

For Microsoft Graph v1.0 API:

<groupId>com.microsoft.graph</groupId>

<artifactId>microsoft-graph</artifactId>

<version>6.0.1-SNAPSHOT</version>

Microsoft Graph Beta API:

<groupId>com.microsoft.graph</groupId>

<artifactId>microsoft-graph-beta</artifactId>

<version>6.0.1-SNAPSHOT</version

GRADLE

For Gradle, you need to add a new repository to tour project:

repositories {

// MavenCentral for resolving dependencies.

mavenCentral()

//Repository for microsoft-graph v6.0

maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }

}

And the dependencies for the API version you want to target. For Microsoft Graph v1.0 API:

implementation 'com.microsoft.graph:microsoft-graph:6.0.1-SNAPSHOT'

And for Microsoft Graph Beta API:

implementation 'com.microsoft.graph:microsoft-graph-beta:6.0.1-SNAPSHOT

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 Java 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 on GitHub! Keep them coming!

For the latest updates, follow @Microsoft365Dev on X (Twitter)

0 comments

Discussion is closed.

Feedback usabilla icon