Simple Guide to Set Up Sitecore GraphQL API for Searching Content

Simple Guide to Set Up Sitecore GraphQL API for Searching Content

·

5 min read

Starting from Sitecore Headless Services version 16.0 and onwards, the Experience Edge for Experience Manager (XM) endpoint is enabled by default. This default configuration allows for limited exposure of Sitecore item information, catering to common front-end requirements in headless Sitecore development.

If you require additional endpoints, you can utilize the Sitecore GraphQL API. This API serves as a versatile GraphQL service platform built on top of Sitecore. It manages your data and offers it through GraphQL queries.

GraphQL is ideal when you need a robust API to support your front-end development. It provides several advantages over traditional REST APIs, including easier maintenance, improved discoverability and query ability due to built-in graphical tools, enhanced bandwidth efficiency, and increased power.

To meet the demands of keyword searching, the Sitecore GraphQL API includes the Content Search API. This API is specifically designed to handle complex search queries that often surpass the capabilities of a generic API. For more detailed examples and information, please refer to the official Sitecore documentation. The following article will provide a straightforward demonstration of the steps involved in using the content search API provided by the Sitecore GraphQL API.

To begin, you need to include the following configuration patch files in the Platform project:

App_Config\Include\Sitecore.Services.GraphQL.Content.Master.config

<?xml version="1.0" encoding="utf-8" ?>

<!--
    Defines the system endpoint for the master database.
-->
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
    <sitecore>
        <api>
            <GraphQL>
                <endpoints>
                    <master url="/sitecore/api/graph/items/master" type="Sitecore.Services.GraphQL.Hosting.GraphQLEndpoint, Sitecore.Services.GraphQL.NetFxHost" resolve="true">
                        <url>$(url)</url>

                        <enabled role:require="ContentDelivery">false</enabled>

                        <enableSubscriptions>true</enableSubscriptions>

                        <!-- lock down the endpoint when deployed to content delivery -->
                        <graphiql role:require="ContentDelivery">false</graphiql>
                        <enableSchemaExport role:require="ContentDelivery">false</enableSchemaExport>
                        <enableStats role:require="ContentDelivery">false</enableStats>
                        <enableCacheStats role:require="ContentDelivery">false</enableCacheStats>
                        <disableIntrospection role:require="ContentDelivery">true</disableIntrospection>

                        <schema hint="list:AddSchemaProvider">
                            <!-- defaults are defined in Sitecore.Services.GraphQL.Content.config -->
                            <content ref="/sitecore/api/GraphQL/defaults/content/schemaProviders/systemContent" param1="master" />
                        </schema>

                        <!-- Determines the security of the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                        <security ref="/sitecore/api/GraphQL/defaults/security/systemService" />

                        <!-- Determines how performance is logged for the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                        <performance ref="/sitecore/api/GraphQL/defaults/performance/standard" />

                        <!--
                            Cache improves the query performance by caching parsed queries.
                            It is also possible to implement query whitelisting by implementing an authoritative query cache;
                            WhitelistingGraphQLQueryCache is an example of this, capturing queries to files in open mode and allowing only captured queries in whitelist mode.
                        -->
                        <cache type="Sitecore.Services.GraphQL.Hosting.QueryTransformation.Caching.GraphQLQueryCache, Sitecore.Services.GraphQL.NetFxHost">
                            <param desc="name">$(url)</param>
                            <param desc="maxSize">10MB</param>
                        </cache>

                        <!-- 
                            Extenders allow modifying schema types after they are created by a schema provider but before they are added to the final schema.
                            This is useful when you want to _extend_ a generated schema, for example to add external API
                            data onto the item API, or to add in custom internal data (e.g. custom layout data to power an app)
                            without having to directly modify a schema provider.

                            Extenders must derive from SchemaExtender.
                        -->
                        <extenders hint="list:AddExtender">
                            <!--<example type="Name.Space.ExtenderType, Assembly" resolve="true" />-->
                        </extenders>
                    </master>
                </endpoints>
            </GraphQL>
        </api>
    </sitecore>
</configuration>

App_Config\Include\Sitecore.Services.GraphQL.Content.Web.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
    <sitecore>
        <api>
            <GraphQL>
                <endpoints>
                    <web url="/sitecore/api/graph/items/web" type="Sitecore.Services.GraphQL.Hosting.GraphQLEndpoint, Sitecore.Services.GraphQL.NetFxHost" resolve="true">
                        <url>$(url)</url>

                        <enabled>true</enabled>

                        <enableSubscriptions>true</enableSubscriptions>

                        <!-- lock down the endpoint when deployed to content delivery -->
                        <graphiql role:require="ContentDelivery">false</graphiql>
                        <enableSchemaExport role:require="ContentDelivery">false</enableSchemaExport>
                        <enableStats role:require="ContentDelivery">false</enableStats>
                        <enableCacheStats role:require="ContentDelivery">false</enableCacheStats>
                        <disableIntrospection role:require="ContentDelivery">true</disableIntrospection>

                        <schema hint="list:AddSchemaProvider">
                            <!-- defaults are defined in Sitecore.Services.GraphQL.Content.config -->
                            <content ref="/sitecore/api/GraphQL/defaults/content/schemaProviders/systemContent" param1="web" />
                        </schema>

                        <!-- Determines the security of the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                        <security ref="/sitecore/api/GraphQL/defaults/security/systemService" />

                        <!-- Determines how performance is logged for the service. Defaults are defined in Sitecore.Services.GraphQL.config -->
                        <performance ref="/sitecore/api/GraphQL/defaults/performance/standard" />

                        <!--
                            Cache improves the query performance by caching parsed queries.
                            It is also possible to implement query whitelisting by implementing an authoritative query cache;
                            WhitelistingGraphQLQueryCache is an example of this, capturing queries to files in open mode and allowing only captured queries in whitelist mode.
                        -->
                        <cache type="Sitecore.Services.GraphQL.Hosting.QueryTransformation.Caching.GraphQLQueryCache, Sitecore.Services.GraphQL.NetFxHost">
                            <param desc="name">$(url)</param>
                            <param desc="maxSize">10MB</param>
                        </cache>

                        <!-- 
                            Extenders allow modifying schema types after they are created by a schema provider but before they are added to the final schema.
                            This is useful when you want to _extend_ a generated schema, for example to add external API
                            data onto the item API, or to add in custom internal data (e.g. custom layout data to power an app)
                            without having to directly modify a schema provider.

                            Extenders must derive from SchemaExtender.
                        -->
                        <extenders hint="list:AddExtender">
                            <!--<example type="Name.Space.ExtenderType, Assembly" resolve="true" />-->
                        </extenders>
                    </web>
                </endpoints>
            </GraphQL>
        </api>
    </sitecore>
</configuration>

App_Config\Include\Sitecore.Services.GraphQL.Serialization.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
    <sitecore>
        <pipelines>
            <owin.cookieAuthentication.validateIdentity>
                <processor type="Sitecore.Owin.Authentication.Pipelines.CookieAuthentication.ValidateIdentity.ValidateSiteNeutralPaths, Sitecore.Owin.Authentication">
                    <siteNeutralPaths hint="list">
                        <path>/sitecore/api/graph/items/</path>
                    </siteNeutralPaths>
                </processor>
            </owin.cookieAuthentication.validateIdentity>
        </pipelines>
    </sitecore>
</configuration>

Save and publish the Platform project.

To enable the GraphQL UI in non-production environments, you can enable debug mode in the web.config file of the CM (Content Management) instance:

MyProject.cm\Web.config

... 
<compilation defaultLanguage="c#" debug="true" targetFramework="4.8"> 
...

Testing queries

  1. Log in to the CM: https://myproject.cm/sitecore

  2. Launch the master endpoint: https://myproject.cm/sitecore/api/graph/items/master/ui

  3. IMPORTANT: Set the request.credentials to same-origin in the Settings.

    If you don't set the request.credentials to same-origin in the Settings, you will encounter an error:
    { "error": { "errors": [ { "message": "Authentication required." } ] } }

  4. Add the sc_apikey to the HTTP HEADERS. Check out this blog post to learn about Sitecore API key:
    { "sc_apikey":"DBA6453F-6A71-4DE9-B9C3-36EA77FCC730" }

  5. Run the following example query to see the results:

{
  search(
    rootItem:"/sitecore/content/myproject/home",    
    fieldsEqual:[
      { name:"_templateName", value:"App Route" }
    ],
    facetOn: [
      "_language"
    ]
    keyword:"graph*",    
    after: "0",
    first: 10
  ) {
    facets {
      name
      values {
        value
        count
      }
    }
    results {
      items {
        id
        name
        path
        templateName
        language
        version
        score
        pageTitle: field(name:"pagetitle")
      }
      totalCount
      pageInfo {
        endCursor,
          hasNextPage,
        hasPreviousPage,
        startCursor
      }
    }
  }
}

Repeat these steps to test the web endpoint: https://myproject.cm/sitecore/api/graph/items/web/ui

In addition to the GraphiQL UI, each GraphQL endpoint offers additional functionalities:

  • $url/schema: This endpoint provides the GraphQL schema in Schema Definition Language (SDL) format. The SDL format is beneficial for static code analysis using tools like eslint-plugin-graphqlm and for schema mocking tools like graphql-tools.

  • $url/stats: Accessing this endpoint displays basic statistics about the schema and performance of the GraphQL endpoint.

  • $url/cache: This endpoint provides detailed information about the GraphQL query cache on the specific endpoint.

https://myproject.cm/sitecore/api/graph/items/web/stats

Finally, for security, the GUI must be disabled in production.

Sitecore Headless Services version 16.0 introduces the Experience Edge for Experience Manager (XM) endpoint as a default feature, providing limited access to Sitecore item information. To enhance API capabilities, developers can leverage the Sitecore GraphQL API, which offers a more comprehensive solution. Additionally, the Content Search API within the Sitecore GraphQL API addresses the need for efficient keyword searching. These advancements empower developers to create more robust and flexible headless Sitecore applications, seamlessly integrating front-end development with Sitecore's content management capabilities.