Tuesday, November 21, 2023

SharePoint Online - Custom Raw Http calls using Graph SDK v5

The Graph SDK is a nuget library to interact with Graph API from .Net applications. Earlier this year they released¹ Graph .Net SDK v5. That highly simplified the coding with fewer lines than v4 but has breaking changes from v4 even in the basic interactions. The good part is that the Graph SDKs simplify the HTTP operations to Graph API but in some cases, we may need to deal with Raw HTTP calls. 

This post discusses such scenarios. A basic idea about Kiota and building API clients using Kiota² is helpful to easily understand the code.

Problem - Custom Url

Support we are dealing with the cutting edge of Graph API, sometimes the API or property in the result may not be available in the Graph SDK as the SDK needs some time to catch up. Unfortunately, no examples can be included due to NDA. In such cases, we need to craft the URL ourselves but we don't need to deal with the authentication. How can we customize the URL in Graph SDK with the result object using the known types in Graph SDK?

Solution

Below is the notebook³ that has the code
Hope the code is self-explanatory. The catch here is the V5 SDK will serialize the result for us. Here we are getting the known Drive object

Problem - Custom URL and Raw JSON results

Sometimes we need to deal with totally custom URLs and the result JSON. In such scenarios, we can only leverage the authentication mechanism of Graph SDK only not even the result object. How can we have a custom HTTP URL and raw JSON result using Graph SDK?

Solution - Using IRequestAdapter

One way is to use the IRequestAdapter and have NativeResponseHandler. The code in a notebook is below. This uses a dummy object to satisfy the adapter and get the JSON via NativeResponseHander.

Solution - Using native HttpClient

The above does not fully give the native experience. To get the feel of native experience we can have the below approach that uses familiar HttpClient.

Please have a look at the warning.

References

¹ - https://devblogs.microsoft.com/microsoft365dev/microsoft-graph-net-sdk-v5-is-now-generally-available/

² - https://learn.microsoft.com/en-us/openapi/kiota/quickstarts/dotnet

³ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-calls.ipynb

⁴ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-IRequestAdapter-json.ipynb

⁵ - https://github.com/dotnet-demos/graph-sdk-sharepoint-online-notebooks/blob/main/custom-rawhttp-HttpClient-json.ipynb

No comments: