A peak into GraphQL for #Sitecore

Through this series I have investigated and shown how to get an environment running, get presenting on a page, and looked at some of the finer points to the JavaScript Services (JSS) SDK code that lays the foundation for a successful site. The final new technical piece to understand in context of headless development with Sitecore is the usage of a GraphQL endpoint.

What is GraphQL?

GraphQL is a query language for your API, and a server-side runtime for executing queries using a type system you define for your data. GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.GraphQL, Introduction to GraphQL, https://graphql.org/learn/

This official definition can be synthesized down to mean "a standard that leverages a strongly-typed query format for accessing data over HTTP."

It is important to note that GraphQL itself is just a set of standards for the mechanism of requesting data from an HTTP endpoint or API and having the return data follow a known format. How the return data is constructed is up to the developer of the endpoint.

To make all this work, what is called a ‘schema’ is required. The schema defines the different types or objects of data and their related properties. By creating this schema of types, it creates a contract with the caller, that the data will comeback in a certain nested format.

Because the caller of the endpoint already knows what form the data takes, they are able to request only the data they for the current downstream action, thus making smaller more efficient calls. Another benefit is that a caller can request multiple types of data at once instead of multiple REST calls, again helping to create a more efficient application.

Some Basic Usage Scenarios

Communication with a GraphQL is usually done through JSON. Queries sent as a GET with the JSON query information encoded as a query string parameter, with return data coming back as JSON. In both instances the JSON must meet the format as defined in the schema, otherwise validation errors will be returned instead of the requested data.

Let’s breakdown some basic data requests against Experience Edge.

Example 1: Get basic information for the site node

# This is the JSON query of data we want
{
    site # request site object 
    {
        # site data is encapsulated in a type called 'siteInfo'
        # within parenthesis you can place specific filtering details for the query based on the schema
        ## in this case to get siteInfo you must tell the query which site to look at
        siteInfo(site:"RainflyAdventures")
        {
            # list of all the fields you want returned, this is a small set of all that can be returned about a site
            name
            rootPath
        }
    }
}

## RESULTS

# note the results only return data per the query 
{
  "data": {
    "site": {
      "siteInfo": {
        "name": "RainflyAdventures",
        "rootPath": "/sitecore/content/RainflyAdventures/RainflyAdventures"
      }
    }
  }
}

Example 2: In this example we will look at returning two different data types in a single query. This will be a request for site information as well as items for navigation construction

{
    # request to get site info
    site{
        siteInfo(site:"RainflyAdventures"){
        name
        sitemap     
        }
    }

    # request for the home node of the site, notice the filtering based on path
    item(language:"en"
         path:"/sitecore/content/RainflyAdventures/RainflyAdventures/home")
    {
        id # Sitecore ID
        displayName 
        hasChildren
        children(hasLayout:true) # filter to get only child items that have layouts, i.e., are a page
        { 
            results # define the fields for each item returned
            {
                name
                path
            }
        }
    }
}

## RESULTS
{
  "data": {
    "site": {
      "siteInfo": {
        "name": "RainflyAdventures",
        "sitemap": [
          "https://edge.sitecorecloud.io/paragon-teachxmcloud-dev-56b4/media/Project/RainflyAdventures/RainflyAdventures/Sitemaps/sitemap.xml"
        ]
      }
    },
    "item": {
      "id": "0EFE3E74988F4182A6160523283C4F76",
      "displayName": "Home",
      "hasChildren": true,
      "children": {
        "results": [
          {
            "name": "About",
            "path": "/sitecore/content/RainflyAdventures/RainflyAdventures/Home/About"
          }
        ]
      }
    }
  }
}

Knowing GraphQL exist is very important, but the JSS SDK does a nice job at providing the mechanics for most basic calls for building your site. That is not to say there won’t be instances where a component needs additional data after a user action, which is when being able to write a custom query maybe needed.

Working with the GraphQL

Sitecore provides an in-browser IDE experience to allow for testing GraphQL requests. The first is called the Delivery API. The Delivery API is a GraphQL API that is hosted on the Delivery Platform and provides access only to approved and published content. This would be calling Experience Edge just like your site. It can be accessed via https://edge.sitecorecloud.io/api/graphql/ide. To successfully make calls you do have to generate a token to include in the header. This would be used in the format of { "X-GQL-Token" : "TOKEN"}

When working in a local, self-hosted environment there is what’s called the Preview API. It uses the exact same schema as the Delivery API, but communicates what is directly on the self-hosted Sitecore XM instance. It can be accessed via https:/YOUR-SITE/sitecore/api/graph/edge/ide. To make the calls successful you will need to create an API key in the Content Tree to include in the header. (This is the same API Key you would have created to allow for the rendering host to communicate.) This would be used in the format of { "sc_api": "API KEY" }

References

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.