Content Hub Tip #16: Demystify your web requests via Web Client SDK

 

Content Hub Tips Logo


When working with the Content Hub, we all come to a certain point in time when we need to write a custom implementation. Sitecore helps us a lot with providing the Web Client SDK. Sitecore describes the SDK as follows:

The Web Client SDK (WebClient) supports scripting through a Scripting SDK as well as supporting code in the Web SDK and the Scripting SDK. The Web Client SDK, however, does not work directly with REST API resources. (Almost) everything REST related has been abstracted away, although the Web SDK still features ways to manage HTTP calls. Furthermore, to provide consistent performance across all services, backend services apply throttling mechanisms. *

* Copied from Sitecore Content Hub documentation

As you can read, a lot of helpful things are already fixed for us out of the box. Which is basically a wrapper around the REST API. Enough about the general stuff. Let's dive into the SDK.

As the SDK is only a wrapper, you would like to see what requests are being sent to the API of Content Hub. Luckily for us, Sitecore got us covered. The IWebMClient interface has an event handler called RequestCreated. By adding your own event handler to this, you can take a peek inside the messages being sent with the SDK.

So how do we set it up? Here an example of how it might look.

public class Program
{
    private static async Task Main()
    {
        MClient.RequestCreated += MClient_RequestCreated;
        await MClient.Querying.QueryAsync(query, EntityLoadConfiguration.Minimal);
    }

    private static void MClient_RequestCreated(object sender, RequestCreatedEventArgs e)
    {
        e.LogContentAsync().Wait();
    }
}

public static class RequestCreatedEventArgsExtensions
{
    public static async Task LogContentAsync(this RequestCreatedEventArgs eventArgs)
    {
        if (eventArgs?.Request?.Content != null)
        {
            var jsonObject = await eventArgs.Request.Content.ReadAsStringAsync();

            Console.WriteLine("######################################");
            Console.WriteLine($"URI: {eventArgs.Request.RequestUri}");
            Console.WriteLine($"JSON: {jsonObject}");
            Console.WriteLine("######################################");
        }
        else
        {
            Console.WriteLine("Could not read Content.");
        }
    }
}

The first thing you need to do is attach your event handler to the existing ones. Make sure to use the += rather than the =. Otherwise, you will overwrite existing functionality that might also depend on the event handler. For easy debugging, I've created a small extension class that you can use to extract the URI and JSON parameters of the request. In the image below, you can find an example request. It will output the URI and the send JSON object.

Example REST API request

Until next time, happy coding!