Skip to content
Darin Larimore
All posts

How to add GraphQL support to a Statamic addon

5 min read
On this page
  1. What you get for free, and why it is useless
  2. Three types and one method
  3. Two wrong guesses
  4. The honest gap
  5. Trying it

Someone opened an issue on my image hotspots fieldtype asking for GraphQL support, for a headless build. I had never needed it on my own sites, none of which run Statamic's GraphQL API, so I had never looked at what a fieldtype has to do to show up in the schema. It turns out to be small. The whole change is 115 lines across five files, and most of it is declaring the shape of the data.

This post is about that one feature, not the general shape of an addon.

What you get for free, and why it is useless

Every fieldtype inherits a toGqlType() from Statamic\Fields\Fieldtype, and the default returns GraphQL::string(). So a custom fieldtype does appear in the schema, typed as a string. For a value that is really an image plus a list of points, each with its own fields, a string is worse than nothing. The client cannot ask for hotspots { x y } because the schema does not know they exist.

The hotspots field saves a value shaped roughly like this:

imageFile:
  url: /assets/kitchen.jpg
  fileName: kitchen.jpg
  alt: The kitchen
hotspots:
  - x: 31.5
    y: 62
    content:
      heading: Island
      body: ...

So the schema needs three types: the field itself, the image, and a hotspot.

Three types and one method

Statamic's GraphQL layer is rebing/graphql-laravel on top of webonyx/graphql-php, and a type is a class extending Rebing\GraphQL\Support\Type with a name and a fields() method. The top-level one:

class ImageHotSpotsType extends Type
{
    public const NAME = 'ImageHotSpots';

    protected $attributes = [
        'name' => self::NAME,
    ];

    public function fields(): array
    {
        return [
            'imageFile' => [
                'type' => GraphQL::type(HotImageType::NAME),
                'resolve' => fn ($data) => $data['imageFile'] ?? null,
            ],
            'hotspots' => [
                'type' => GraphQL::listOf(GraphQL::type(HotspotType::NAME)),
                'resolve' => fn ($data) => $data['hotspots'] ?? [],
            ],
        ];
    }
}

$data in the resolvers is the field's augmented value, the same array the Antlers tag sees. HotImageType is four string fields (url, id, fileName, alt). HotspotType is two floats and a content field, which I will come back to.

Then the fieldtype hands back its type:

public function toGqlType()
{
    return GraphQL::type(ImageHotSpotsType::NAME);
}

and the service provider registers the three classes so that GraphQL::type('ImageHotSpots') can find them by name:

public function bootAddon()
{
    ImageHotSpots::register();

    GraphQL::addType(ImageHotSpotsType::class);
    GraphQL::addType(HotImageType::class);
    GraphQL::addType(HotspotType::class);
}

That is the feature. The query in the README works against it:

{
  imageHotspots {
    imageFile { url id fileName alt }
    hotspots { x y content }
  }
}

Two wrong guesses

The first commit did not work, and the fixes are more instructive than the feature.

I had guessed that the top-level type should extend Statamic\GraphQL\Types\Fieldtype. There is no such class. Statamic's own concrete types in Statamic\GraphQL\Types (ReplicatorSetType, GridItemType, AssetType) extend Rebing's Type directly, and so should yours. The second commit, an hour later, is one line: extends Type.

That fix caused the next bug. The file had imported GraphQL\Type\Definition\Type from webonyx for Type::listOf(), and swapping the import to Rebing's Type meant Type::listOf now pointed at a class that has no such method. The third commit, that evening, replaced it with GraphQL::listOf(). The Statamic facade has string(), float(), listOf(), nonNull() and type(), which is every helper I needed, and once everything goes through the facade the imports stop being a place to make mistakes. Use the facade for all of it.

The honest gap

The content field on a hotspot is typed as Statamic's Array scalar:

'content' => [
    'type' => GraphQL::type(ArrayType::NAME),
],

That is an untyped blob. The client gets whatever JSON is in there and cannot select fields inside it. The reason is that a contributor made hotspot content a configurable set of fields in November 2024, so the shape depends on each blueprint and there is no single content type to declare. Statamic's Replicator solves the same problem properly: its addGqlTypes() builds one type per set from the field config at schema time, and its toGqlType() returns a list of those. That is the right next step for this addon, and it is a bigger job than the three fixed types above. For the person who asked, the blob was enough to unblock them, so it shipped.

A note on registration while you are here. I registered the types eagerly in bootAddon(). Core also offers an addGqlTypes() hook on the fieldtype, which blueprints call when they build their own types, and it is the right place when your types depend on the field's config the way Replicator's do. For fixed types, the service provider is fine.

Trying it

GraphQL is off by default. Set STATAMIC_GRAPHQL_ENABLED=true, enable the collection in config/statamic/graphql.php under resources, and the query above runs at /graphql. None of my own sites have that flag on, which is exactly why the request came from someone else, and why the first attempt extended a class that does not exist. Read core's own types before you guess.