Sitecore Item Service Rest APIs for Client Apps

The Item Service REST API allows you to interact with Sitecore items directly. This is very useful specially when you want to develop a data-driven client application including JavaScript application to interact with the Sitecore items without having Sitecore context. 

Sitecore.Services.Client provides two services:

  • ItemService: This service gives you access to regular Sitecore items.
  • EntityService: This service gives you access to business objects that you define.

In this article, I will show you the implementation of the Item Service API using .NET Console application.

The ItemService REST API allows the following operations:

  • CRUD - Create, Read, Update and Delete Item
  • Sitecore Search
  • Execute Stored Item Queries

You may refer the Official Sitecore Documentation – ItemService REST API for more details.

Request and Response flow: This is pretty straightforward flow where you need to authenticate first with the respective Sitecore instance and then perform the different requests as needed within the same authentication session. 

Let's proceed with the implementation using .NET Console application

1. Create one Console Application and name it as you wish. For me this is SitecoreServiceClientAPIConsole.

2. Let's create one model class to authenticate the request.

 public class AuthModel
 {
    [JsonProperty("domain")]
    public string Domain { get; set; }

    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }
 }
3. In this example we are going to create an item in Sitecore under Global folder. So let's create one ItemRequest model. 
public class ItemRequest
{
   public string TemplateID { get; set; }
   
   public string ItemName { get; set; }

   public string Title { get; set; }

   public string Description { get; set; }
}
4. Before implementing main method in the console application, we need to patch one config change in Sitecore to make it working.
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
    <settings>
      <setting name="Sitecore.Services.SecurityPolicy">
        <patch:attribute name="value"
        value="Sitecore.Services.Infrastructure.Web.Http.Security.ServicesOnPolicy, Sitecore.Services.Infrastructure" />
      </setting>
    </settings>
  </sitecore>
</configuration>
5. Now, it's a time to create a method in consto authenticate the request.
  • Note - I have used ServiceAPI user to authenticate this request but it's up to you to create a separate user with the required privileges for the same purpose.
    private static void AuthRequest(ref CookieContainer cookies)
    {
        var authUrl = "https://<YOUR-SITECORE-URL>/sitecore/api/ssc/auth/login";

        var authModel = new AuthModel
        {
            Domain = "sitecore",
            Username = "ServicesAPI",
            Password = "xxxxxx"
        };

        var authRequest = (HttpWebRequest)WebRequest.Create(authUrl);

        authRequest.Method = "POST";
        authRequest.ContentType = "application/json";

        var requestAuthBody = JsonConvert.SerializeObject(authModel);

        var authBytes = new UTF8Encoding().GetBytes(requestAuthBody);

        using (var dataStream = authRequest.GetRequestStream())
        {
            dataStream.Write(authBytes, 0, authBytes.Length);
        }

        authRequest.CookieContainer = cookies;

        var authResponse = authRequest.GetResponse();

        Console.WriteLine($"Login Status:\n\r{((HttpWebResponse)authResponse).StatusDescription}");

        authResponse.Close();
    }
6. Let's define a method to create an item in Sitecore. 
    private static void CreateItem(CookieContainer cookies)
    {
        var itemRequest = new ItemRequest
        {
            ItemName = "API Test Item",
            TemplateID = "{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}", // Your template Id expected here.
            Title = "API Test Item Title",
            Description = "API Test Item Description"
        };

        var url = "https://<YOUR-SITECORE-URL>/sitecore/api/ssc/item/sitecore/content/<YOUR-GLOBAL-FOLDER-PATH>";

        var request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";
        request.ContentType = "application/json";
        request.CookieContainer = cookies;

        var requestBody = JsonConvert.SerializeObject(itemRequest);

        var data = new UTF8Encoding().GetBytes(requestBody);

        using (var dataStream = request.GetRequestStream())
        {
            dataStream.Write(data, 0, data.Length);
        }

        var response = request.GetResponse();

        Console.WriteLine($"Item Status:\n\r{((HttpWebResponse)response).StatusDescription}");
    }
7. Now it's a time to implement the main method to create an item in Sitecore. 
    public static void Main(string[] args)
    {
        try
        {
            //Auth Request
            CookieContainer cookies = new CookieContainer();
            AuthRequest(ref cookies);

            //Create Item Request
            CreateItem(cookies);

        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error occurred. Message: {ex.Message}.\r\n StackTrace: {ex.StackTrace}.\r\n InnerException: {ex.InnerException}");
        }

        Console.ReadKey();
    }
If you have noticed in the above code, I have used CookieContainer to store the authentication cookie and the same cookie is passed to the CreateItem function to authenticate the request while creating an item is Sitecore.

That's it! Once the above code is successfully compiled and run, you should see the new item created in the Sitecore at the specified path.

Comments

Popular posts from this blog

Setup Sitecore XM Cloud Dev Environment using Docker

Sitecore Content Hub - Triggers, Actions and Scripts

All Blog Posts - 2023