Create GraphQL schemas
Schemas describe the way that data is organized and constructed.
If your Sitecore instance contains data or business logic not exposed through the Sitecore-provided GraphQL schemas, you might want to create your own schema provider. You can use a schema provider to add self-contained pieces of a schema.
If you want to add a new root query and your type system does not depend on any other schema provider’s types, you must select a schema provider. A good example of a schema provider is a third-party CRM system.
Implement a schema provider
Implement a schema provider
To implement a schema provider:
-
Create a C# class that implements the
SchemaProviderBaseclass. This class defines the structure of the GraphQL schema, including the root fields that can be queried (an item is a root query field in the content schema provider). You create other supporting classes that define graph types (the node types in the schema). -
Register the schema provider on a GraphQL endpoint. This is a type registration in the endpoint’s config patch.
The following example shows a complete schema provider implementation. It allows querying on the current Sitecore user:
This example uses nested classes because the schema is small. Real schemas are larger, and we recommend you split RootFieldTypes and GraphTypes into separate files.
To register the schema provider with an endpoint, use a Sitecore config patch file similar to this:
Extend GraphQL schemas
Extend GraphQL schemas
You can modify or add to an existing schema by using an extender. Extenders are processed after schema providers, and they can modify or add types to the completed schema. This means that they can modify or add to the schema from more than one schema provider. Use an extender if you want to add a field to an existing type provided by a schema provider, hook an external API onto an existing type, or otherwise modify the schema provided by a schema provider.
A good example of when you use an extender is if you want to get API data from an item that contains a third-party API ID, such as a YouTube video ID: You can use the YouTube API to retrieve the description of the video and expose it via GraphQL alongside the Video item type.
To extend a GraphQL schema:
-
Create a schema extender with a class that extends the
SchemaExtenderclass and a registration with theGraphQLendpoint in configuration, similar to a schema provider: -
The following example shows registering an extender on a GraphQL endpoint: