Beta Version

BLOGS

Amit Thapliyal
5 Minute read

Consuming Sitecore Items RESTful API for External Integrations

Sitecore manages content very neatly and systematically in the form of a tree. You can manage your organization data easily using Sitecore. Your data needs to serve a broad range of clients active on the web browsers, mobile, different mobile applications and other integrated services of your website. The Restful API is the way to fulfill these requirements. The output can be configured on JSON or XML format.

The blog is primarily written to help you learn how to create and use REST API to expose Sitecore data for your different customers and users.

1. I have created some bios in Sitecore as below

Sitecore RESTful API

2. Add an interface “IBioInfo.cs”

using System.ServiceModel;

using System.ServiceModel.Web;

using CommonLibrary;

namespace SitecorePOC

{

    [ServiceContract]

    public interface IBioInfo

    {

        [OperationContract]       

        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "?ID={BioID}&All={All}")]

        BioList GetBio(string bioID, bool All);

    }

}

Digital Customer Engagement - ebook

ebook

Digital Customer Engagement for Asset & Wealth Management Companies

3. You need to add WCF Data Service in your web project. Let us add a service with the name “BioInfo.svc” which will implement the interface IBioInfo.cs

Sitecore RESTful API 2

//------------------------------------------------------------------------------

// <copyright file="WebDataService.svc.cs" company="Microsoft">

//     Copyright (c) Microsoft Corporation.  All rights reserved.

// </copyright>

//------------------------------------------------------------------------------

using CommonLibrary;

using System.ServiceModel.Activation;

namespace SitecorePOC

{

    [AspNetCompatibilityRequirements(

    RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    public class BioInfo : IBioInfo

    {

        public BioList GetBio(string bioID, bool All)

        {

            BioList bioList = new BioList();

            return bioList.GetAllBios(bioID, All);

        }

    }

}

4. GetBio method internally calls a function GetAllBios of CommonLibrary where actual logic is implemented to get the data based on parameters.

using Sitecore.Data.Items;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization; 

namespace CommonLibrary

{

    [DataContract]

    public class BioList

    {

        public BioList()

        {

        }

        private List<Bios> iPeople = new List<Bios>();

        [DataMember(Order = 1)]

        public List<Bios> Persons { get { return iPeople; } set { iPeople = value; }

}

 

        public BioList GetAllBios(string bioID, bool All)

        {

            Sitecore.Context.SetActiveSite("website");

            BioList BioList = new BioList();

            List<Bios> item = new List<Bios>();

            //Getting a specific bio feed based on its GUID

            if(!string.IsNullOrEmpty(bioID))

            {

                var bioItem =  Sitecore.Context.Database.GetItem(bioID);

                if (bioItem != null)

                {

                    Bios bio = new Bios()

                   {

                       Title = bioItem.Fields["Title"].Value,

                       Email = bioItem.Fields["Email"].Value,

                       GUID = bioItem.ID.ToString(),

                       FirstName = bioItem.Fields["FirstName"].Value,

                       LastName = bioItem.Fields["LastName"].Value

                   };

 

                    item.Add(bio);

                }

            }

            //Getting all bio feed irrespective of GUID

            if (All)

            {

               var Bios = Sitecore.Context.Database.GetItem("/sitecore/content/Home/Bios").Children;

               foreach (Item bioItem in Bios)

                {

                    Bios bio = new Bios()

                    {

                        Title = bioItem.Fields["Title"].Value,

                        Email = bioItem.Fields["Email"].Value,

                        GUID = bioItem.ID.ToString(),

                        FirstName = bioItem.Fields["FirstName"].Value,

                        LastName = bioItem.Fields["LastName"].Value

                    };

 

                    item.Add(bio);

                }

             }

            return new BioList

            {

                Persons = item.ToList()

            };

        }

    }

}       

5. You need to add a DataContract

 

                    using System.Runtime.Serialization;

                          namespace CommonLibrary

                 {

                       [DataContract]

                 public class Bios

             {

                    [DataMember(Order = 0)]

                   public string GUID { get; set; }

                     [DataMember(Order = 1)]

                   public string Title { get; set; }

                    [DataMember(Order = 2)]

                    public string FirstName { get; set; }

                    [DataMember(Order = 3)]

                    public string LastName { get; set; }

                     [DataMember(Order = 4)]

                     public string Email { get; set; }

    }

6. In web.config file, just add the highlighted behaviors and services

<system.serviceModel>

    <bindings>

      <basicHttpBinding>

        <binding name="SitecoreApplicationCenter" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:20:00" sendTimeout="00:05:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">

          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />

        </binding>

      </basicHttpBinding>

    </bindings>

    <behaviors>

      <serviceBehaviors>

        <behavior name="web">

          <serviceMetadata httpGetEnabled="true" />

          <serviceDebug includeExceptionDetailInFaults="false" />

        </behavior>

      </serviceBehaviors>

    </behaviors>

    <services>

      <service name="SitecorePOC.BioInfo" behaviorConfiguration="web">

        <endpoint address="" binding="webHttpBinding" contract="SitecorePOC.IBioInfo" ></endpoint>

      </service>

    </services>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

  </system.serviceModel>

7. After building the project, when you will hit the urls, you will able to get output as XML which can be consumed anywhere. 

  1. http://sitecorepoc/bioinfo.svc/?All=true
  2. Sitecore RESTful API 3
  3. http://sitecorepoc/bioinfo.svc/?ID={DD87A2B9-0D43-4EB7-A54B-8B113B27F06A}

    Sitecore RESTful API 4

  4. To Get JSON output, you need to change WebMessageFormat from Xml to Json


    Sitecore RESTful API 5

Altudo in partnership with Sitecore is fully committed to enable brands across verticals to woo their customers across all channels by creating exceptional customer experiences with 1:1 personalized content.

Check out our capabilities to know more about how we enable brands to build Revenue Engine using Sitecore.

If you have Sitecore implemented as your CMS and are looking to build a mobile application for Omnichannel CX, drop us a line at marketing@altudo.co

Amit Thapliyal
Amit Thapliyal Global Marketing Director, Altudo


You might like these

Supercharge Digital Marketing ROI with the Revenue Engine

In the digital era, businesses that can hold 1:1 customer conversations across channels will win the lion’s share of revenue.

Read More...
Supercharge Digital Marketing ROI with Revenue Engine

3 Best Ways to make Website Search more engaging for a Law Firm

Users can quickly form an opinion about your website, based on quality of search results. We take a deep dive into the top 3 ways to website search more engaging. Read More...
Sitecore 9 Features & their capabilities

The 7 Best Sitecore 9 Features and Their Capabilities

To enjoy Sitecore 9 and its features to their full potential, you need to be aware of their capabilities. You also need to identify the areas where you could expect these capabilities to make the maximum impact.

Read More...
Make website search more engaging for a Law Firm

Get in Touch