Magento2 How to create a custom GraphQL

Magento2 How to create a custom GraphQL

GraphQL is a query language for APIs, gives clients the power to ask for exactly what they need and nothing more. GraphQL uses mutations to perform CRUD operations.

Today we will only talk about creating and query a simple GraphQL api. Let us begin by creating schema.graphqls under etc directory:

Vendor/Module/etc/schema.graphqls

Now add following content to the file:

type Query
{
    getMyPost(id: Int @doc(descrition: "Post ID. Must be an integer")): GetMyPostData
        @resolver(class: "Vendor\\Module\\Model\\Resolver\\MyPost")
        @doc(description: "Gets all posts data")
}
type GetMyPostData
{
    id: Int
    title: String
    categories: [String]
    description: String
}

Next add the MyPost resolver model: Vendor/Module/Model/Resolver/MyPost.php

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

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

class MyPost implements ResolverInterface
{
    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        if (!isset($args['id'])) {
            throw new GraphQlInputException(__('Invalid Parameter provided.'));
        }

        $id = $args['id'];

        $allposts = $this->getAllPosts();
        $post = [];
        foreach ($allposts as $item) {
            if ($id == $item['id']) {
                $post = $item;
                break;
            }
        }

        return $post;
    }

    public function getAllPosts(): array
    {
        return [
            [
                "id" => 1,
                "title" => "My Post 1",
                "categories" => ["my posts", "custom posts"],
                "description" => "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
            ],
            [
                "id" => 2,
                "title" => __("My Post 2"),
                "categories" => ["my posts", "custom post2"],
                "description" => "Lorem Ipsum is simply dummy text of the printing and typesetting industry."
            ],
        ];
    }
}

Time to run our graphQL api. Use postman or a GraphQL client to test the request. I usually use Altair GraphQL chrome extension to run the request.

In url specify {base_url}/graphql and add following query under query or request body section:

query {
  getMyPost(
    id: 2
  ) {
    title
    categories
    description
  }
}

The output will be:

GraphQL custom API Response

Leave a Reply

Your email address will not be published.