Learn how to create your own custom GraphQL queries and mutations in Magento 2.
- Module Structure
- Creating a Simple Query
- Creating a Query with Arguments
- Creating a Mutation
- Input Types
- Output Types
- Extending Existing Types
- Complex Nested Resolvers
- Filtering and Pagination
- Complete Example: Blog Module
By the end of this section, you will be able to:
- Create a custom Magento module with GraphQL support
- Define custom queries and mutations
- Create resolvers to handle data fetching
- Use input and output types
- Extend existing Magento GraphQL types
- Implement filtering and pagination
- Build a complete custom GraphQL API
app/code/Vendor/CustomGraphQL/
├── etc/
│ ├── module.xml
│ └── schema.graphqls
├── Model/
│ └── Resolver/
│ └── HelloWorld.php
├── registration.php
└── composer.json
type Query {
helloWorld: String @resolver(class: "Vendor\\CustomGraphQL\\Model\\Resolver\\HelloWorld") @doc(description: "Returns a hello world message")
}<?php
namespace Vendor\CustomGraphQL\Model\Resolver;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
class HelloWorld implements ResolverInterface
{
public function resolve(
Field $field,
$context,
ResolveInfo $info,
array $value = null,
array $args = null
) {
return "Hello, GraphQL World!";
}
}{
helloWorld
}Expected response:
{
"data": {
"helloWorld": "Hello, GraphQL World!"
}
}type Query {
customProduct(sku: String!): CustomProductOutput
@resolver(class: "Vendor\\Module\\Model\\Resolver\\CustomProduct")
}type Mutation {
createCustomEntity(input: CustomEntityInput!): CustomEntityOutput
@resolver(class: "Vendor\\Module\\Model\\Resolver\\CreateCustomEntity")
}
input CustomEntityInput {
name: String!
description: String
status: Int
}
type CustomEntityOutput {
entity_id: Int
name: String
success: Boolean
message: String
}Start with Module Structure to learn how to set up your custom module.
← Previous: Built-in Functionality | Back to Main | Next: Resolvers Deep Dive →