Consuming Sitecore Items RESTful API for external Integrations
Home

Consuming Sitecore Items RESTful API for external Integrations

Author: Anurag Agarwal | Categories: Website Design & User Experience, Websites, Design & Ux

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, CMS

         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);

    }

}

 

 

       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, CMS

 

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

// <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

Sitecore, CMS

 

     ii. http://sitecorepoc/bioinfo.svc/?ID={DD87A2B9-0D43-4EB7-A54B-8B113B27F06A}

 Sitecore, CMS

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

 Sitecore, CMS

 

       iv. http://sitecorepoc/bioinfo.svc/?ID={DD87A2B9-0D43-4EB7-A54B-8B113B27F06A}

Sitecore, CMS