Skip to main content

GraphQL for Sitecore: A beginner walkthrough

If you are a beginner in GraphQL and you are looking step-by-step by process to setup GraphQL API on Sitecore, please proceed further and setup up GraphQL API for Sitecore

Before we jump start Sitecore GraphQL API, let us start some basic introduction of GraphQL.

What is GraphQL
  • GraphQL is a query language
  • GraphQL provides a complete and understandable description of the data in your API
  • It gives the power to ask exactly what you need and nothing more
  • Designed to support the needs of the front-end
  • Strongly typed, self-documenting
  • Bandwidth efficient
  • Easy real-time data
Sitecore GraphQL API
  • The Sitecore GraphQL API is a generic GraphQL service platform on top of Sitecore. It hosts your data and presents it through GraphQL queries. The API supports real-time data using GraphQL subscriptions
  • Get GraphQL by installing the JSS server components package
  • Sitecore GraphQL does not have any GraphQL endpoints defined by default
  • Define at least one endpoint to use the GraphQL API
Prerequisites : Required Installations
  • Sitecore 9 or later
  • Sitecore JavaScript Services Server for Sitecore 9.3 XP 13.0.0 rev. 190924.zip
  • Check for your Sitecore version compatible package
Prerequisites : Required Settings
  • Make sure you did set <compilation debug=”true”> in the Web.config
  • Make sure that you set * for AllowedControllers and CORS Origins in your API Key item  for development environment
  • If you use GraphQL subscriptions or WebSocket transport, you must enable the WebSockets feature on the IIS and reset the IIS afterwards
How to setup GraphQL for Sitecore

Sitecore GraphQL currently ships as a component of JavaScript Services
Step1: If you have not already installed Sitecore JavaScript Services Server for Sitecore 9.3 XP 13.0.0 rev. 190924.zip, install this using installation wizard
Step2: Generate API Key under the below path in Sitecore /sitecore/system/Settings/Services/API Keys
Step3: As mentioned earlier, enter * in CORS Orgins field and Allowed Control fields. For Impersonation User field, enter extranet\anonymous as the default user and publish. Note: this is for development environment
Step4: Enable Sitecore.Services.GraphQL.Content.Master.config under  the path <webroot>\App_Config\Sitecore\Services.GraphQL
Step5: Configure security setting for local dev environment in  Sitecore.Services.GraphQL.config
Step6: Browse this url on this browser https://<your_domain>/sitecore/api/graph/items/master/ui

Running a simple query






Anatomy of a Query
  • A GraphQL query has its own syntax
  • Request and Responses are of same shape
  • Queries looks like JSON

An example of a GraphQL Query:








Another example of a GraphQL Query:








Querying the API

Running multiple queries in a single request







Fetch only what is required in a single query






Running multiple queries in a single request by passing parameters









Running a search query









Documentation Explorer
  • Documentation explorer is equally important. Auto-generating API documentation of GraphQL keeps documentation in sync with API changes
  • GraphQL documentation explorers enable developers to understand syntax and browse the documentation in a useful way















GraphQL approaches for Sitecore

Integrated GraphQL:

Integrated GraphQL operates by storing the GraphQL query in the component GraphQL Query field on the rendering

Connected GraphQL:

A JSS app makes the direct HTTP requests to a Sitecore GraphQL endpoint

REST API vs GraphQL

REST                                                                             GraphQL
A lot of endpoints                                                          Single endpoint
Over fetching or under fetching of data                     Fetch only what you need
Multiple versioning                                                        No versioning required
Difficulty in understanding                                             Self documented

Pros and Cons of GraphQL

Pros
  • Being less “talkative” than REST makes GraphQL way faster
  • Good fit for complex systems and micro services
  • Fetching data with a single API call
  • No over- and under-fetching problems
  • Tailoring requests to your needs
  • Validation and type checking out-of-the-box
  • Auto-generating API documentation
  • API evolution without versioning
Cons
  • Performance issues with very complex queries
  • Overkill for small applications
  • Web caching complexity
  • File uploading
  • Queries always return a HTTP status code of 200 irrespective error
  • Takes a while to understand
  • Tech community
When to use GraphQL
  • GraphQL is appropriate when you need a production-grade API to power different frontend applications.  Ex: Apps for devices such as mobile phones, smartwatches, and IoT devices,      where bandwidth usage matters
  • When you don’t want to implement REST API. Applications where nested data needs to be fetched in a single call. Ex: a blog or social networking platform where posts need to be fetched along  with nested comments and commenters details
  • When your applications heavily uses API from its front-end(s) or expose its API to external consumers
That's all I wanted present with this article and if in case if you are looking for help in setting up your first Sitecore JSS app. Visit here for my other page.

Here is the youtube link of the presentation https://www.youtube.com/watch?v=4OVudHsjoMw 

Comments

  1. I am trying to execute below query to create Item,but it is throwing error,Can you please suggest what I am doing wrong.

    mutation{
    createItem(name:"SampleItem1",template:"{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}",parent
    :"{C42A194A-B619-4EF9-949F-7FFD43716F2D}",fields:{
    name:"Title",value:"I Love GraphQL",
    }) {
    id
    }
    }

    ReplyDelete
    Replies
    1. I Got what I am doing wrong here

      mutation{
      createItem(name:"SampleItem1",template:"{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}",parent
      :"{C42A194A-B619-4EF9-949F-7FFD43716F2D}",fields:{
      name:"Title",value:"'I Love GraphQL'",
      }) {
      id
      }
      }

      Delete
  2. This is really an awesome piece on Graphql espicially for beginners, really appreciate it.

    ReplyDelete

Post a Comment

Popular posts from this blog

Steps to create a Sitecore JSS app and Deploy to Sitecore

If you are a beginner in Sitecore JSS and you are looking step-by-step by process to setup your first JSS App with Sitecore, please proceed further and setup up your first JSS App along with deploying it to Sitecore. Before we jump start creating JSS APP, let us start with a quick introduction to Sitecore JSS. What is Sitecore JSS?  Sitecore JavaScript Services (JSS) is a complete SDK for JavaScript developers that enables you to build full-fledged solutions using Sitecore and modern JavaScript UI libraries and frameworks. Build Headless JavaScript applications with the power of Sitecore. Use your favorite JavaScript framework powered by an enterprise experience platform like React, Angular or Vue.js. Prerequisites for Connected mode with Sitecore Required Installations node.js v6.9 or later npm v5.7 or later Sitecore 9 or later installation with JSS(For JSS component ref, https://dev.sitecore.net/Downloads/Sitecore_JavaScript_Services.aspx) Required Settings  Sitecore

Custom Fields in Sitecore (Custom DropLink, DropTree, MultiList, TreeList and Required Field Validator)

Custom Fields in Sitecore Just thought to share few of the custom Sitecore fields that I have created for one of the sample project. This may help the community memebers to easily incorporate them into their project if they need any of them. Here are few. 1. Custom DropLink using Sitecore.Data.Items; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; namespace SitecoreCustom.Web.Extensions.CustomFields { public class CustomDropLink : Sitecore.Shell.Applications.ContentEditor.LookupEx { protected override void DoRender(System.Web.UI.HtmlTextWriter output) { this.ExcludeItems(); base.DoRender(output); } private void ExcludeItems() { Item item = Sitecore.Context.ContentDatabase.GetItem(base.ItemID); var LinkedField= Sitecore.StringUtil.ExtractParamete

Sitecore JSS - Custom Rendering Content Resolvers

In Sitecore, while working for real-time projects, you may get scenarios where you would see a need to customize you rendering output to serialze. Sitecore provides three different ways of customizing your rendering output with Sitecore JSS. They are as below. • Use JSS GraphQL Support - Using Integrated GraphQL queries • Use Out-of-the-box Rendering Content Resolvers - Using Sitecore JSS built-in Rendering Content Resolvers • Implementing a Custom Rendering Content Resolvers by inheriting RenderingContentsResolver Why Customization? In Sitecore development, many times we encounter scenarios to deal with hierarchical item structures like multi-level menu, product category, product sub-category, product details, forms etc., and even, in case where there is a need to combine the Sitecore data with any non-Sitecore data. In these types, Sitecore JSS is not able to serialize item structures with sub-hierarchies into JSON. Sitecore Jss allow us custiomize in