Creating a New GraphQL Endpoint in Magento 2

Creating a new GraphQL endpoint in Magento 2 allows you to expand the functionality of your API, making it easier to retrieve and manipulate data. This guide will walk you through the process of creating a new GraphQL endpoint from scratch.

Step-by-Step Guide to Creating a New GraphQL Endpoint

Step 1: Create a Custom Module

Create a new module, for instance, Vendor/Module.

Step 2: Define the Schema and Declare the Resolver

Create the schema.graphqls file in app/code/Vendor/Module/etc.

type Mutation {
  customMutation(input: CustomInput!): CustomOutput @resolver(class: "Vendor\\Module\\Model\\Resolver\\CustomMutation")
}

input CustomInput {
  data: String!
}

type CustomOutput {
  result: String
}

Step 3: Implement the Resolver

Create a resolver class in app/code/Vendor/Module/Model/Resolver.

<?php
namespace Vendor\Module\Model\Resolver;

use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Config\Element\Field;

class CustomMutation implements ResolverInterface
{
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        return ['result' => 'Mutation executed successfully with data: ' . $args['input']['data']];
    }
}

Testing the New Endpoint

Use a tool like GraphiQL or Postman to test your new mutation endpoint. Here’s an example mutation query:

mutation {
  customMutation(input: { data: "test data" }) {
    result
  }
}

Conclusion

Creating a new GraphQL endpoint in Magento 2 involves defining a schema, implementing resolvers, and declaring them in the dependency injection configuration. By following these steps, you can create powerful new endpoints to extend your Magento 2 store’s functionality.

For more information on using and extending GraphQL in Magento 2, check out the previous parts of this series:

Updated: