Getting Started with GraphQL Queries in Sitecore: A Practical Guide

Introduction

GraphQL in Sitecore provides a powerful and flexible way to interact with content programmatically. In this guide, we'll explore how to set up GraphQL in Sitecore and implement various query operations for building efficient headless applications.

Sitecore GraphQL API framework:

       Queries (reading data)

       Mutations (altering data)

       Subscriptions (subscribing to real-time updates of data)



Setting Up GraphQL in Sitecore

       Navigate to the `App_config` folder in your Sitecore root directory

       Locate the `Services.GraphQL` folder

       Rename the file “Sitecore.Services.GraphQL.Content.Master.config.example” to “Sitecore.Services.GraphQL.Content.Master.config”.

Add Authentication

Enable GraphQL using API Key

       Open AppConfig\Sitecore\Services.GraphQL\Sitecore.Services.GraphQL.config

       In security section make the following changes


Enable site-neutral paths

       Browsing Sitecore instance URL may give Authentication error as below

       modify the Sitecore.Owin.Authentication.Config file to include site-neutral paths.

       go to the Sitecore installation folder path

       :\inetpub\wwwroot[SC installed folder]\App_Config\Sitecore\Owin.Authentication.

       find the Sitecore.Owin.Authentication.Config file to edit.

       search “siteNeutralPaths” node and add the path “/sitecore/api/graph/items/” underneath it and save the changes.


Check GraphQL query in playground

       Open the Rendering

       Go to GraphQL section

       Click “Open Xgraph Browser”



To execute query, we need to add two things

HTTP HEADERS: pass the API key

QUERY VARIABLE: pass contextItem path

Adding API Key to Sitecore

       Go to the location /sitecore/system/Settings/Services/API Keys

       Right click on the API Keys folder and insert a new API Key

       Give API Key a unique name

       Insert * in CORS Origins and Allowed Controllers fields


Template and content structure for example

We defined a structure of Leaders and Team members as below to perform query operations




Settings and Queries:


HTTP HEADERS 
{
     "sc_apikey":"{00000000-0000-0000-0000-000000000000}"
}
QUARY VARIABLE 
{
     "datasource":"/sitecore/content/Home/DemoProject/Home/About"
}


1. Get Name and Value for all the fields including standard fields 

query GQLAllFieldsNameValueQuery($datasource: String!) {
  item(path: $datasource, language: "en") {
    fields
    {
      name
      value
    }
  }
}




2. Get own fields - to get only own template fields/excludes standard fields

query GQLGetOnlyTemplateFieldsQuery($datasource: String!) {
  item(path: $datasource, language: "en") {
    fields(ownFields: true) {
      id
      name
      value
    }
  }
}

3. Query to get mentioned fields of the template item

query GetItemTemplateFieldsGQLQuery($datasource: String!) {
  responseData: item(path: $datasource, language: "en") {
    id
    name
    ... on About {
      title {
        value
      }
      subtitle {
        value
      }
      image {
        alt
        src
      }
      link {
        url
      }
      date {
        value
      }
      isTrue {
        value
      }
    }
  }
}


4. Get children based on given template 

query GQLFilterByTemplateQuery($datasource: String!) {
  item(path: $datasource, language: "en") {
    children {
      ... on Leader {
        id
        name
        department{
           value
         }
        module{
           value
         }
      }
    }
  }
}

5. Get Multilist/treelist fields

query GQLGetMultilistItemsQuery($datasource: String!) {
  responseData: item(path: $datasource, language: "en") {
    id
    name
    ... on About {
      title {
        value
      }
      subtitle {
        value
      }
      image {
        alt
        src
      }
      multiListItems {
        id
        name
        targetItems {
          id
          name
          ... on Leader {
            department {
              value
            }
            leaders {
               id
               name
               targetItems {
                id
                name
                ... on LeaderDetailsHead{
                  type{
                    value
                  }
                  bio{
                    value
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

6. Get field values using Alias

query GQLGetFieldWithAliasQuery($datasource: String!) {
  responseData: item(path: $datasource, language: "en") {
    RootItemId: id
    ... on About {
      Title: subtitle {
        value
      }
      Subtitle: description {
        value
      }
    }
  }
}



7. Search based on a field value

{
  search(fieldsEqual:[{name:"Name", value:"Nidhi" }]  
    rootItem: "/sitecore/content/Home/DemoProject/Home/About/Leaders/PM") {
    results {
      items {
        item {
          id
          name
          path
          url
          FirstName: field(name  : "Name") {
           value
          }
         Designation: field(name  : "Designation") {
           value
          }
          Bio: field(name  : "Bio") {
           value
          }
        }
      }
      totalCount
    }
  }
}

8. Search based on a keyword

{
  search(keyword:"TL"
  rootItem:"/sitecore/content/Home/DemoProject/Home"
  ) {
    results {
      totalCount,
      items{
        id
        name
        path
      }
    }
  }
}

9. Getting multiple data source items data

query GetDataFromMultipleSourceQuery($datasource: String!) {
  responseData: item(path: $datasource, language: "en") {
    name
    Leaders: children(
      includeTemplateIDs: ["{B5D116DE-BFE8-4A06-A3FE-90C84320ECCB}"]
    ) {
      name
      ... on Leader{
        department{
          value
        }
      }
    }
    Team: children(
      includeTemplateIDs: ["{1D1B624B-3D93-496C-9E0F-D5417B4B3CA0}"]
    ) {
      name
      ... on Team{
        department{
          value
        }
      }
    }
  }
}


10. To see full layout - Experience edge only

query {
  layout(site: "DemoProject", routePath: "/", language: "en") {
     item {
      rendered
    }
  }
}


When implementing GraphQL queries in Sitecore, take care of below points:

 1. Security

   - Always implement proper authentication

   - Use API keys securely

   - Restrict access to sensitive data

 

2. Performance

   - Monitor query performance

   - Implement proper caching strategies

   - Optimize query structure

 

3. Error Handling

   - Implement comprehensive error handling

   - Validate input data

   - Handle null values appropriately

 

4. Content Modeling

   - Follow Sitecore's best practices

   - Use appropriate field types

   - Structure content hierarchically

 

Next Steps

This guide covers the fundamentals of GraphQL queries in Sitecore. In upcoming posts, we'll explore:

- Mutations for content manipulation

- Using Fragments for query optimization

- Advanced search operations

- Integration with frontend frameworks

 

Stay tuned for more detailed explorations of these topics!


Comments

Popular posts from this blog

Setting Up Sitecore Headless with Next.js in Disconnected Mode

Translating Sitecore items’ field values into different language with PowerShell and Translate API

Create Sitecore Ribbon Button using Sitecore PowerShell Extensions