Working with GraphQL
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
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.
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 :
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.
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:
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
You can use a tool such as 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 !
Resolvers, like any other Magento class, can be extended using , 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.