Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 42 ยท Admin, APIs and Backend Services

GraphQL in Magento

Extend Magento's GraphQL API: write schema.graphqls, connect fields to resolvers, add queries and mutations, handle errors and understand caching, with PHP stand-ins.

REST gives a client a fixed answer for every URL. If a mobile screen needs only a product's name and price, it still receives everything the endpoint returns, and if it needs the product plus its reviews, it makes two calls. Magento also ships a GraphQL API, where the client sends a query that lists exactly the fields it wants and gets back JSON in the same shape. It is the API that headless storefronts such as PWA frontends use most.

In this lesson you will learn how a GraphQL module is built: a schema file, a resolver class for each field, queries, mutations, errors and the caching rules. Real Magento code is read-only here, because Magento cannot run on this site. The runnable examples are plain PHP stand-ins: a resolver map that executes a small query and a mutation with error handling. If you have seen the REST side, see The REST API; both reach the same services.

The shape of a GraphQL module

A module that adds GraphQL needs very little:

  • etc/schema.graphqls describes the types, queries and mutations in the GraphQL schema language.
  • A resolver class for each field that cannot be answered from its parent's data.
  • A dependency on the core GraphQL module, declared in module.xml with <sequence><module name="Magento_GraphQl"/></sequence> (see Module Sequence and Dependencies).

All schema files from all modules are merged into one schema, much like the XML merging described in Areas and Configuration Files. The endpoint is /graphql. Queries can be sent with GET, and mutations must use POST.

schema.graphqls

The schema file is plain GraphQL with Magento directives. This read-only example adds a query for one badge and a mutation to create one:

GRAPHQL
type Query {
    acmeBadge(
        id: Int! @doc(description: "The badge id")
    ): AcmeBadge
        @resolver(class: "Acme\\Badge\\Model\\Resolver\\Badge")
        @doc(description: "Returns one badge")
}

type Mutation {
    createAcmeBadge(input: AcmeBadgeInput!): AcmeBadge
        @resolver(class: "Acme\\Badge\\Model\\Resolver\\CreateBadge")
        @doc(description: "Creates a badge")
}

type AcmeBadge @doc(description: "A product badge") {
    id: Int
    label: String
    color: String
}

input AcmeBadgeInput {
    label: String!
    color: String
}

Points worth knowing:

  • Int! means a required argument. The ! is GraphQL's non-null marker.
  • @resolver(class: "...") names the PHP class that computes the field. Inside the schema string, the namespace separator is written as a double backslash.
  • @doc adds a description that shows up in tools such as GraphiQL.
  • input types are used for mutation arguments; type is used for output.
  • To add a field to an existing core type, you declare the same type again with only your extra fields, and Magento merges the declarations. Adding fields to core types is how a module returns its data inside a standard product query.

Resolvers

A resolver implements Magento\Framework\GraphQl\Query\ResolverInterface. Its resolve() method receives the field being resolved, a context object, information about the query, the parent value, and the arguments (read-only code):

PHP
namespace Acme\Badge\Model\Resolver;

use Acme\Badge\Api\BadgeRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

class Badge implements ResolverInterface
{
    public function __construct(private BadgeRepositoryInterface $badgeRepository)
    {
    }

    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        ?array $value = null,
        ?array $args = null
    ) {
        if (empty($args['id'])) {
            throw new GraphQlInputException(__('The "id" value is required.'));
        }
        try {
            $badge = $this->badgeRepository->getById((int) $args['id']);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
        }
        return [
            'id' => $badge->getId(),
            'label' => $badge->getLabel(),
            'color' => $badge->getColor(),
        ];
    }
}

Three habits are worth building:

  1. Return an array whose keys match the schema field names. The GraphQL engine reads the requested fields from it.
  2. Inject a service contract, not a model or the object manager. The resolver is a thin adapter: it validates, calls a repository and shapes the result.
  3. Throw the GraphQL exceptions (GraphQlInputException, GraphQlNoSuchEntityException, GraphQlAuthorizationException), so the response carries a clean error with a category instead of a raw stack trace.

The $context object carries per-request information such as the current store and the user. Resolvers that expose customer data check it and refuse anonymous callers.

A resolver map you can run

The stand-in below keeps a map from Type.field to a resolver function. The executor walks the requested fields and calls the resolver for each. Fields that the parent array already contains are returned directly (GraphQL's "default resolver"). Only requested fields appear in the output, which is the main benefit of GraphQL.

flowchart TB
    Q["Query<br/>acmeBadge(id: 5) { label color }"] --> E["Executor"]
    E -->|"Query.acmeBadge"| R1["Resolver: Badge"]
    R1 --> A["array id, label, color"]
    A -->|"only requested fields"| O["JSON: label, color"]

The executor calls the resolver for the root field, then picks only the fields that the query asked for.

PHP A resolver map and field selection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first query received only label and color, although the resolver returned more. The second reached into the nested product and picked its name. The third asked for an unknown id, so the field resolved to null. In the real engine, a nullable field becomes null while a non-null field with a failure produces an error and nulls the parent.

Mutations and errors

A mutation is a field on the Mutation type, and works like a resolver for writing data. The convention is an input object argument that is validated inside the resolver. Customer-bound mutations also check the context for a logged-in user. Failures are reported in an errors array in the response. The HTTP status is typically 200 even then, so clients must always check for errors.

The next stand-in creates a badge, validates the input and uses an isLoggedIn flag from a context object. It collects errors like GraphQL does, in a list with a category instead of throwing out of the whole request.

PHP A mutation with validation and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Only the valid call stored a row. Every failure path returned an error with a category and left the data untouched. In Magento the resolver would call a repository save() instead of a store, but the validation and exception pattern is the same.

Caching at a glance

Because queries can be sent with GET, they can be cached by the full page cache or by Varnish. You mark a field as cacheable with the @cache directive and, for entity data, supply a cache identity class that returns tags such as acme_badge_5. When the badge changes, those tags are invalidated, as explained in Indexers and Caching. Fields without the @cache directive tell Magento that the whole response must not be cached. A single uncacheable field in the query makes the entire response uncacheable, so keep per-customer data such as a cart in a separate query from public catalog data. Mutations always use POST and are never cached.

Other facts that help in practice: send a Store header with the store view code to get store-specific data and prices; send Authorization: Bearer <customer token> for customer queries; and keep queries shallow, since a deeply nested query that asks for hundreds of items can overload a server. Magento enforces limits on query depth and complexity, configured in the deployment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file declares a module's GraphQL types, queries and mutations?

    schema.graphqls is written in the GraphQL schema language, and the files from all modules are merged into one schema.
  2. 2. What does the @resolver directive do?

    The class given in @resolver implements ResolverInterface and its resolve() method returns the data for the field.
  3. 3. A resolver cannot find the requested entity. What should it throw?

    GraphQL exceptions are translated into the errors array with a category. A generic exception leaks internals or produces a vague message.
  4. 4. Why should customer-specific data and public catalog data be in separate queries?

    Cacheability is decided per response. One uncacheable field makes the full response uncacheable.

Summary

  • GraphQL lets the client choose the fields it receives; Magento exposes it at /graphql, with GET for queries and POST for mutations.
  • A module defines types in etc/schema.graphqls and connects fields to PHP classes with @resolver(class: "...").
  • A resolver implements ResolverInterface, validates arguments, calls a service contract and returns an array shaped like the schema.
  • Throw GraphQlInputException, GraphQlNoSuchEntityException or GraphQlAuthorizationException so errors are clean and categorized; clients must check the errors array.
  • The @cache directive with identity tags makes GET queries cacheable; one uncacheable field makes the whole response uncacheable.
  • Use the Store header for store views and a bearer token for customer data.

Next: Cron Jobs and Message Queues