Working with GraphQL

ScandiPWA requests the data it needs from Magento via GraphQL. By default, Magento already defines a GraphQL schema and corresponding resolvers, enabling the frontend to request certain data via GraphQL. However, the API provided by Magento is not complete, so ScandiPWA has a set of custom modules that extend it to serve a broader range of data.

If you need develop custom backend functionality in your site, or if you want to adapt existing functionality to ScandiPWA, you will need to make sure it can be accessible via GraphQL.

Technically, you could fetch data using a REST API as well, but this has several disadvantages and is discouraged in favor of GraphQL. The ScandiPWA codebase entirely uses GraphQL.

Defining a Query

A GraphQL schema describes what types of data the GraphQL server deals with, what queries and mutations it provides, as well as the expected parameters and responses of those queries.

Queries and Mutations in GraphQL are like GET and POST request endpoints in REST – they implement one specific functionality of the API. A key difference is that all queries and mutations are done through one actual endpoint, managed by GraphQL. This allows for more flexibility. You can read an introduction to GraphQL if you are not familiar with it.

In Magento, you can extend the schema by creating a GraphQL schema file, at etc/schema.graphqls in your module. The schema files from all modules get merged together to producs the final schema, accessible to the frontend. This means that you can define new queries or types, as well as extend existing types.

Consider this example schema:

scandipwa/catalog-graphql/src/etc/schema.graphqls (annotated excerpt)
# this block contains the queries we define in this schema file
type Query {
    category (
        id: Int @doc(description: "Ids of the category")
        url_path: String @doc(description: "Url path of the category")
    ): CategoryTree
    @resolver(class: "ScandiPWA\\CatalogGraphQl\\Model\\Resolver\\CategoryTree")

# this type is already defined elsewhere; we merely want to add
# another field to it
type CategoryTree {
    is_active: Boolean @doc(description: "Category is enabled")

In GraphQL, types followed by an exclamation mark ! are required. Since we have specified id: Int and not id: Int!, neither of the parameters are required.

This schema defines a new GraphQL query that accepts either an id or url_path and returns a category. The CategoryTree type is already defined elsewhere fields representing a category, so we don't need to re-define that. We do, however, want to add a new field to specify if the category is enabled.

Implementing a Resolver

A GraphQL resolver is a piece of PHP code that actually implements the queries defined in the Schema. It takes the query parameters as function arguments, and must return a PHP array or associative array of the shape specified in the schema.

The query defined in the schema above specifies a resolver class using the @resolver annotation. The Magento GraphQL mechanism will use this class whenever a cmsPage query is made.

By convention, resolvers are located in the Model/Resolver directory of the module. All resolvers must implement the Magento\Framework\GraphQl\Query\ResolverInterface to ensure they are able to work with the GraphQL system.

Here is the resolver used by the category query:

scandipwa/catalog-graphql/src/Model/Resolver/CategoryTree.php (simplified)
class CategoryTree implements ResolverInterface
    // [...] field declarations, constructor using dependency injection

     * @inheritdoc
    public function resolve(
        Field $field,
        $context, // some context info (e.g. the user ID if any)
        ResolveInfo $info,
        array $value = null,
        array $args = null // an associative array of the parameters passed
    ) {
        $rootCategoryId = $this->getCategoryId($args);

        // a bunch of helper functions.
        // $category ends up being an array-like value with the data we want
        $categoriesTree = $this->categoryTree->getTree($info, $rootCategoryId);
        $result = $this->extractDataFromCategoryTree->execute($categoriesTree);
        $category = current($result);

        return $category;

When writing most simple resolvers, you will need to know:

  • $context contains some information about the user's session

  • $args contain the arguments passed to the query/mutation

  • The function must return an array containing the data you want the query to return

Testing the Query

You can use a tool such as Altair GraphQL or another GraphQL client to check that your query is working properly. The GraphQL endpoint, by default, is <your-server>/graphql.

If your query works as expected, you can now use it on the frontend!

Extending Existing Resolvers

Resolvers, like any other Magento class, can be extended using Magento Plugins (interceptors), or the DI preference mechanism. You can also extend the GraphQL types of their responses to specify that they now return some new field as well.

Last updated