Start using Sitecore GraphQL API

Abstract

Describes how to set up and start using GraphQL with Sitecore

This topic describes how you set up and use the Sitecore GraphQL API. You get GraphQL by installing the JSS server components package.

To set up Sitecore GraphQL:

  1. In the web.config file, set <compilation debug="true">. This enables the GraphQL GUI with the default security settings. For security, the GUI is disabled in production scenarios by default.

  2. If you use GraphQL subscriptions or WebSocket transport, you must enable the WebSockets feature on the IIS and then reset the IIS.

    Note

    WebSockets are not supported on Windows Server 2008 R2 and earlier. You cannot use subscriptions when hosted on these operating systems.

  3. If you use CORS or impersonation, set up an SSC API key in the master:/sitecore/system/Settings/Services/API Keys folder. API keys work with GraphQL in the same way as with Sitecore Services Client.

In Sitecore Headless Services 16.0 and later, the Edge Preview endpoint is enabled by default, but you can configure additional endpoints.

To configure a GraphQL endpoint:

  • Define at least one endpoint to use the GraphQL API.

    The following example defines a content API endpoint with required authentication for the Master database:

    <?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 modify a schema provider directly.
                            
                                Extenders must derive from SchemaExtender.
                            -->
                            <extenders hint="list:AddExtender">
                                <!--<example type="Name.Space.ExtenderType, Assembly" resolve="true" />-->
                            </extenders>
                        </master>
                    </endpoints>
                </GraphQL>
            </api>
        </sitecore>
    </configuration>
    

    Note

    The Sitecore GraphQL default configuration files are a good resource for understanding the configuration options available. The default presets that are referred to with ref in the endpoint configuration are especially interesting. The files are in the /App_Config/Sitecore/Services.GraphQL folder.

When you have defined a GraphQL endpoint, it can be accessed by the URL you defined it with. For example, you could query the API with a URL similar to this: http://my.sitecore.domain/sitecore/api/graph/items/master.

It is, however, much easier to compose queries in the GraphiQL GUI. You access the GUI by adding /ui to the endpoint URL: http://my.sitecore.domain/sitecore/api/graph/items/master/ui. You can compose GraphQL queries using schema-powered auto-completion in the GUI, test queries, and review the documentation of the schema.

With the previous configuration example, to use the GraphiQL GUI to create queries:

  1. Log in to Sitecore (the example endpoint requires authentication).

  2. Go to /sitecore/api/graph/items/master/ui. This UI lets you query items and templates in the Master database.

  3. Click the Docs link to browse the type schema. 

  4. Write a GraphQL query using GraphiQL code completion functionality (pressing CTRL-Space triggers it manually). The following query, for example, retrieves an item, its children, and its template definition in a single query:

    {
      item(path: "/sitecore/templates") {
        id
        path
        children {
          name
        }
        template {
           fields {
            name
          }
        }
      }
    }
    

    The result (abbreviated) is similar to this:

    {
      "data": {
        "item": {
          "id": "{3C1715FE-6A13-4FCF-845F-DE308BA9741D}",
          "path": "/sitecore/templates",
          "children": [
            {
              "name": "Branches"
            },
            {
              "name": "Sample"
            },
            ...
          ],
          "template": {
            "fields": [
              {
                "name": "__Help link"
              },
              ...
            ]
          }
        }
      }
    }
    

Note

If the endpoint requires authentication, so does the GUI. If the endpoint requires an SSC API key (?sc_apikey=api-key-guid), the GUI also requires the API key.

Querying the API

There is nothing special about querying the Sitecore GraphQL API compared to any other GraphQL endpoint. We recommend that you use a client library such as Apollo.

Sitecore GraphQL endpoints support all types of GraphQL requests:

  • HTTP POST with application/json content type and query in the standard JSON payload format.

  • HTTP POST with application/json content type and JSON array of standard payloads (used for batching).

  • HTTP POST with application/json using the Automatic Persisted Queries protocol to reduce the size of the queries.

  • HTTP POST with application/graphql content type and raw GraphQL query in the body.

  • HTTP GET with query string parameters (query, operationName, variables).

  • WebSocket with the graphql-ws protocol (subscriptions or queries).

All types of GraphQL operations are supported by the API framework (a schema might or might not implement all of these kinds of operations):

  • Queries (reading data).

  • Mutations (altering data).

  • Subscriptions (subscribing to real-time updates of data).

Subscriptions are implemented by using the Apollo subscriptions-transport-ws protocol, which uses WebSockets. Socket connections are automatically allowed to GraphQL endpoint URLs. 

Additional features

In addition to the GraphiQL /ui, each GraphQL endpoint also supports some additional pieces:

  • $url/schema - dumps the GraphQL schema in Schema Definition Language (SDL) format. The SDL format is useful for static code analysis, with tools like the eslint-plugin-graphqlm, and schema mocking tools such as graphql-tools.

  • $url/stats - shows basic statistics about the endpoint schema and its performance.

  • $url/cache - shows details about the GraphQL query cache on the endpoint.

Note

You can disable each of these extra endpoint features with config patches for the web.config file: 

<enableSchemaExport role:require="ContentDelivery">false</enableSchemaExport>
<enableStats role:require="ContentDelivery">false</enableStats>
<enableCacheStats role:require="ContentDelivery">false</enableCacheStats>