Connecting and Fetching Data from Sitecore Content Hub

Welcome, Sitecorians!👋 Today, we're diving into how to establish a connection with Sitecore Content Hub and retrieve data efficiently. Whether you're a developer looking to integrate Sitecore Content Hub into your applications or just keen on understanding the process, this blog post will walk you through from introduction to code implementation.


Before we start, make sure you have: Access to a Sitecore Content Hub instance and the necessary API credentials (Username and Password).


Authentication to Obtain an Access Token

To interact with Sitecore Content Hub's API, we first need to authenticate and obtain an access token. Here's how you can achieve this using C#:

Code Snippet for Authentication:

public string GetAccessToken()
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://{{www.marketingcontenthub.com}}/api/authenticate");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize(new
        {
            user_name = "your username",
            password = "your password"
        });

        streamWriter.Write(json);
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        if (!string.IsNullOrEmpty(result))
        {
            var response = JsonConvert.DeserializeObject<TokenStatus>(result);
            return response.Token;
        }
    }
    return string.Empty;
}

This method sends a POST request to the /api/authenticate endpoint with the username and password, receiving an access token in response.

Model Class for Token Status:

public class TokenStatus
{
    public string Token { get; set; }
}

This simple class is used to deserialize the JSON response from the authentication request, extracting the access token.

Fetching Assets with the Access Token:

Once we have the access token, we can use it to fetch assets from Sitecore Content Hub. Here’s how:

Code Snippet to Fetch Assets:


public AssetRoot GetAsset(string token)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://{{www.marketingcontenthub.com}}/api/search");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    httpWebRequest.Headers.Add("X-Auth-Token", token);

    AssetRoot obj = new AssetRoot();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"defaults\":\"SearchConfiguration\"," +
            "\"configuration_category\":\"PortalConfiguration\"," +
            "\"sorting\":{\"field\":\"None\"," + "\"asc\":false}," +
            "\"skip\":0," + "\"take\":100}";

        streamWriter.Write(json);
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        obj = Newtonsoft.Json.JsonConvert.DeserializeObject<AssetRoot>(result);
    }
    return obj;
}

public class AssetRoot
{
    public string query { get; set; }
    public int totalItemCount { get; set; }
    public List<Item> items { get; set; }
   
}
public class Item
{
    public int id { get; set; }
    public Properties properties { get; set; }
    public DateTime created_on { get; set; }
    public int version { get; set; }
    public Full full { get; set; }
    public Renditions renditions { get; set; }
}

public class Properties
{
    public string Title { get; set; }
    public bool HasDuplicate { get; set; }
}

public class Full
{
    public string href { get; set; }
}

public class Renditions
{
    public List<Thumbnail> thumbnail { get; set; }

}

public class Thumbnail
{
    public string href { get; set; }
}

This method constructs a POST request to the /api/search endpoint, including the access token in the headers. It sends a search query and receives a list of assets in response, which are deserialized into an AssetRoot object. 

By following these steps, you can authenticate and fetch data from Sitecore Content Hub using direct HTTP requests in C#. This approach provides a straightforward way to integrate Sitecore Content Hub into your applications, allowing you to manage and utilize your digital assets effectively. 

Remember to replace placeholder values like URLs, username, and password with your actual credentials and endpoint. Happy coding, Sitecorians!
Post a Comment (0)
Previous Post Next Post