Sitecore Item Web API Client: Create

This is a quick update to announce that the client library now supports item creation operations. There are a couple of considerations that need to be taken into account with regards to Security

  1. You must update the itemwebapi.access attribute for the target site in Sitecore.ItemWebApi.config to ReadWrite
  2. You must use an AuthenticatedSitecoreDataContext
  3. The user must have create permissions on the parent item
  4. To update the newly created items fields, the user must have write permissions for the item

Warning!

When creating new items you can define the parent item using Sitecore query, to be sure where your new item will be created limit the scope of the query to match a single item e.g. avoid things such as descendant selectors.

Example

var credentials = new SitecoreCredentials();

credentials.UserName = "sitecore\\foo";
credentials.Password = "bar";

var context = new AuthenticatedSitecoreDataContext("host", credentials);

var query = new SitecoreCreateQuery();

// the name of the new item
query.Name = "Foo";

// the id of the parent item
query.ItemId = "{11111111-1111-1111-1111-111111111111}";

// alternatively specify the parent with a query
// if you specify the ItemId it will take precedence
query.ParentQuery = "/sitecore/content/Home";

// Template can be a template id, branch id or path relative to the
// sitecore/Templates folder
query.Template = "{11111111-1111-1111-1111-111111111111}";
query.Database = "master";

query.FieldsToUpdate = new Dictionary<string, string>();

// fields can be specified by name or id
query.FieldsToUpdate.Add("Field Name", "Value");
query.FieldsToUpdate.Add("{11111111-1111-1111-1111-111111111111}", "Value");

// only return the fields we updated in the response to validate the operation
query.FieldsToReturn = new List<string>();
query.FieldsToReturn.Add("Field Name");
query.FieldsToReturn.Add("{11111111-1111-1111-1111-111111111111}");

ISitecoreWebResponse response = context.GetResponse(query);

if (response.StatusCode == HttpStatusCode.OK)
{
    Console.WriteLine(response.Result.Count);
    
    foreach (WebApiItem item in response.Result.Items)
    {
        Console.WriteLine(item.Path);
    }
}

Download the code here

Advertisements

Sitecore Item Web API Client: Update

This is a quick update to announce that the client library now supports field update operations. There are a couple of considerations that need to be taken into account with regards to Security

  1. You must update the itemwebapi.access attribute for the target site in Sitecore.ItemWebApi.config to ReadWrite
  2. You must use an AuthenticatedSitecoreDataContext
  3. The user must have write permissions on the item

Warning!

Field update queries are affected by the scope parameter. If the query is scoped to the parent or children of the item that matches the query or item id the fields on the parent and child items will also be updated.

Example

Update queries can be used with either item or expression queries. In the case of expression queries, all items matching the query will be updated.

var credentials = new SitecoreCredentials();

credentials.UserName = "sitecore\\foo";
credentials.Password = "bar";

var context = new AuthenticatedSitecoreDataContext("host", credentials);

var query = new SitecoreItemQuery();

// the id of the item to update
query.ItemId = "{11111111-1111-1111-1111-111111111111}";

query.Database = "master";

query.FieldsToUpdate = new Dictionary<string, string>();

// fields can be specified by name or id
query.FieldsToUpdate.Add("Field Name", "Value");
query.FieldsToUpdate.Add("{11111111-1111-1111-1111-111111111111}", "Value");

// only return the fields we updated in the response to validate the operation
query.FieldsToReturn = new List();
query.FieldsToReturn.Add("Field Name");
query.FieldsToReturn.Add("{11111111-1111-1111-1111-111111111111}");

ISitecoreWebResponse response = context.GetResponse(query);

if (response.StatusCode == HttpStatusCode.OK)
{
    Console.WriteLine(response.Result.Count);

    foreach (WebApiItem item in response.Result.Items)
    {
        Console.WriteLine(item.Path);
    }
}

Download the code here

Sitecore Item Web API Client: Delete

This is a quick update to announce that the client library now supports delete operations. There are a couple of considerations that need to be taken into account with regards to Security

  1. You must update the itemwebapi.access attribute for the target site in Sitecore.ItemWebApi.config to ReadWrite
  2. You must use an AuthenticatedSitecoreDataContext
  3. The user must have delete permissions in order to delete items. The easiest way to check if this is the case is to use Sitecore’s Security Access Viewer

Warning!

Deleting items is permanent. Deleted items do not go into the recycle bin so please use with caution. Also, the Sitecore Item Web API returns a count of the number of items that were deleted as a result of the query, this count shows you the total number of items that were matched by the query and successfully deleted, it does not also include a count of the descendant items that may have gone with them.

Example

var credentials = new SitecoreCredentials();

credentials.UserName = "sitecore\\foo";
credentials.Password = "bar";

var context = new AuthenticatedSitecoreDataContext("host", credentials);

var query = new SitecoreItemQuery(SitecoreQueryType.Delete);

query.ItemId = "{11111111-1111-1111-1111-111111111111}";

// a safeguard, limit the scope of the deletion
query.QueryScope = new[] { SitecoreItemScope.Self };

// another safeguard, items can always be re-published
query.Database = "web";

ISitecoreWebResponse response = context.GetResponse(query);

if (response.StatusCode == HttpStatusCode.OK)
{
    Console.WriteLine(response.Result.Count);

    // the ids of the items deleted (does not include descendants)
    if (response.Result.ItemIds != null)
    {
        foreach (string id in response.Result.ItemIds)
        {
            Console.WriteLine(id);
        }
    }
}

Download the code here

Sitecore Item Web API Client Library

The Sitecore Item Web API is an officially supported module released by Sitecore in November 2012. In its initial release the purpose of the module is to provide developers with programmatic access to a Sitecore instance so that items can be manipulated through code.

Sitecore’s official explanation goes as follows… Developers use the Sitecore Item Web API to manipulate the content items in Sitecore through HTTP requests. The API gives access to content through items paths, IDs, and Sitecore queries. This service produces output in JSON format and is both highly customizable and optimized to support a minimum number of requests.

Most of us who have been working with Sitecore over the years will no doubt have written custom web services to support systems integrations using Sitecore as a central content repository so this module is a very welcome addition. To get my hands dirty with the module and understand its capabilities I decided to write a client library in C# so that

  1. I had an excuse to write code!
  2. My life would be easier if I have the need to “talk” to the Item Web API from a .NET application outside of Sitecore
  3. I could share the code with all of you and hopefully get some feedback

I will point out at this point that the Item Web API supports multiple operation types read, create, delete etc. The first revision of the client library only supports read operations. I will be adding support for the additional operations over the next few weeks.

Update: the client now supports

  1. Read
  2. Create
  3. Update
  4. Delete

Installing the Sitecore Item Web API

Before I jump into the library and sample code I will point out a fairly obvious pre-requisite. You must have url access to a Sitecore instance that has the Item Web API installed. Installing the Item Web API is extremely straight forward

  1. Download the module from the Sitecore Developer Network
  2. The module is basically a Sitecore package, install it using the installation wizard
  3. Configure security by editing Sitecore.ItemWebApi.config, which can be found in {WebRoot}\App_Config\Include (NOTE: if you decide to use authentication the user must belong to the extranet domain and you must specify the fully qualified name in the username header)
  4. If you are using authentication and want to switch to the master database the user must belong to the Sitecore Client Users role

Library Examples

The key objects are:

  1. SitecoreDataContext
  2. AuthenticatedSitecoreDataContext
  3. SitecoreExpressionQuery
  4. SitecoreItemQuery
  5. SitecoreWebResponse
  6. WebApiItem
  7. WebApiField

Using these types (as demonstrated below) you will see how quickly you can get up and running and querying a remote Sitecore instance. The code is available to clone on github and comes with a demo project that covers typical scenarios.

Configuration

The library uses the popular log4net library to log requests, successes, failures etc. In order for this to function properly you need to tell the project where you plan to store the Config\SitecoreWebApiClient.config file. You can do this by simply editing the ConfigurationFilePath in the project settings

Anonymous Requests

To send an anonymous request we first have to create a new instance of SitecoreDataContext. By default it is assumed that the request will not be sent by SSL but you can pass an optional additional boolean parameter into the constructor of SitecoreDataContext to override the assumption

var context = new SitecoreDataContext("host");

Now that we have a data context we can use it to send two types of queries

Expression Queries

Expression queries request items using Sitecore query

var query = new SitecoreExpressionQuery(SitecoreQueryType.Read);

query.Query = "/sitecore/content/Home/*";

Item Queries

Item queries send a request for a specfic item using an item id

var query = new SitecoreItemQuery(SitecoreQueryType.Read);

query.ItemId = "{11111111-1111-1111-1111-111111111111}";

Sitecore Web Response

Now that we have a data context and a query we can pass the query into the GetResponse method of the data context to get a SitecoreWebResponse. A SitecoreWebResponse has properties that tell us about the status of the response and if successful the item data returned by the Sitecore Item Web API

ISitecoreWebResponse response = context.GetResponse(query);

if (response.StatusCode == HttpStatusCode.OK)
{
    foreach (WebApiItem item in response.Result.Items)
    {
        // the Key property of the KeyValuePair holds the field id
        foreach (KeyValuePair<string, WebApiField> field in item.Fields)
        {
            Console.WriteLine("fieldid: " + field.Key);
            Console.WriteLine("fieldname: " + field.Value.Name);
            Console.WriteLine("fieldtype: " + field.Value.Type);
            Console.WriteLine("fieldvalue: " + field.Value.Value);
        }
    }
}

Authenticated Requests

The two query examples above can also be used with an authenticated request. To do so instead of creating a new instance of SitecoreDataContext we create a new instance of AuthenticatedSitecoreDataContext, which expects a parameter of type SitecoreCredentials in it’s constructor. You can optionally choose to send encrypted authentication headers

var credentials = new SitecoreCredentials();

credentials.UserName = "extranet\\foo";
credentials.Password = "bar";
credentials.EncryptHeaders = true;

var context = new AuthenticatedSitecoreDataContext("host", credentials);

ISitecoreWebResponse response = context.GetResponse(query);

There are many more parameters that the Sitecore Item Web API allows us to specify and they are all supported by the item query types including

  • Database
  • Language
  • Fields
  • Payload
  • Scope
  • Paging

To try these options out download the code and experiment away! Once again this is currently read only, I will post updates on this blog when more operations become available.

Update: the client now supports

  1. Read
  2. Create
  3. Update
  4. Delete