Get CMS Pages collection using Graphql Magento 2.

Get All CMS pages using GraphQl in Magento 2 by a simple module.

We can get all the CMS Pages collection by GraphQl by just create the Resolver model and add our custom logic for getting all the CMS Pages collection. You can add a filter to the condition for getting specific CMS Pages in the Resolver PHP file.

If you want to know Out of the Box Magento cmsPage Query, Refer a link with more explanation, Cms Page, and Cms Blocks GraphQL Query in Magento. 

I hope you are aware of What is GraphQl and how GraphQL is used for the programming language like Magento 2 If You are new to GraphQL check the link for GraphQl in Magento.

Now we can start the module using Magento 2 for fetch all the CMS Pages.

You need to create the first registration.php and module.xml file for defining our module.

I have taken Packagename as Rbj and Modulename as CmsPagesGraphQl.

Path: app/code/Rbj/CmsPagesGraphQl/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Rbj_CmsPagesGraphQl',
    __DIR__
);

Create module.xml file, Path: app/code/Rbj/CmsPagesGraphQl/etc/module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Rbj_CmsPagesGraphQl">
        <sequence>
            <module name="Magento_Cms"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

Our Module depends on GraphQL and CMS Module so we have given the dependency on module.xml file for each module.

Every GraphQl Module must contain schema.graphqls file under the etc folder of a module.

schema.graphqls is at the center of any GraphQL Query implementation and describes what data can be queried. So You can define your query data basic skeleton under the schema.graphqls file.

Path: app/code/Rbj/CmsPagesGraphQl/etc/schema.graphqls

type Query {
    cmsPages: CmsPages @resolver(class: "Rbj\\CmsPagesGraphQl\\Model\\Resolver\\CmsPages") @doc(description: "Get all CMS static pages from store.")
}

type CmsPages @doc(description: "Cms Pages graphql gather Data of all CMS page information") {
    allPages: [PagesRecord] @doc(description: "An array containing the all the CMS Page from Magento")
}

type PagesRecord {
    identifier: String @doc(description: "Identifier of CMS Page")
    name: String @doc(description: "Get name of CMS Page")
    page_layout: String @doc(description: "Get page layout of CMS Page")
    content: String @doc(description: "Content of CMS Page")
}

Now Create a Resolver Model for our custom module.
Rbj\\CmsPagesGraphQl\\Model\\Resolver\\CmsBlock
CmsBlock Resolver Model class which is defined in schema.graphql file at above. In this Model, the resolve() method will simply return data of all the CMS Pages.

Path: app/code/Rbj/CmsPagesGraphQl/Model/Resolver/CmsPages.php

<?php
declare(strict_types=1);

namespace Rbj\CmsPagesGraphQl\Model\Resolver;

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

/**
 * CMS Pages field resolver
 */
class CmsPages implements ResolverInterface
{
    public function __construct(
        \Magento\Cms\Api\PageRepositoryInterface $pageRepositoryInterface,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->pageRepositoryInterface = $pageRepositoryInterface;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $pagesData = $this->getPagesData();
        return $pagesData;
    }

    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    private function getPagesData(): array
    {
        try {
            /* filter for all the pages */
            $searchCriteria = $this->searchCriteriaBuilder->addFilter('page_id', 1,'gteq')->create();
            $pages = $this->pageRepositoryInterface->getList($searchCriteria)->getItems();
            $cmsPages['allPages'] = [];
            foreach($pages as $page) {
                $cmsPages['allPages'][$page->getId()]['identifier'] = $page->getIdentifier();
                $cmsPages['allPages'][$page->getId()]['name'] = $page->getTitle();
                $cmsPages['allPages'][$page->getId()]['page_layout'] = $page->getPageLayout();
                $cmsPages['allPages'][$page->getId()]['content'] = $page->getContent();
            }
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
        }
        return $cmsPages;
    }
}

Now Run Upgrade command to install our module.

php bin/magento setup:upgrade
php bin/magento cache:flush

You can check your GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon.

You can check the query results in a browser using Google Chrome ChromeiQl addOn.

cms pages graphql
cms pages graphql

In Request Body, You need to pass the required data(field) to request payload for getting a response of CMS Pages,

In Request Body, You need to pass the required data(field) to request payload for getting a response of CMS Pages,

Request Payload

{
  cmsPages {
    allPages {
      name
      identifier
      content
      page_layout
    }
  }
}

Result: The result will be all CMS Pages collection,

{
  "data": {
    "cmsPages": {
      "allPages": [
        {
          "name": "404 Not Found",
          "identifier": "no-route",
          "content": "<dl>\r\n<dt>The page you requested was not found, and we have a fine guess why.</dt>\r\n<dd>\r\n<ul class=\"disc\">\r\n<li>If you typed the URL directly, please make sure the spelling is correct.</li>\r\n<li>If you clicked on a link to get here, the link is outdated.</li>\r\n</ul></dd>\r\n</dl>\r\n<dl>\r\n<dt>What can you do?</dt>\r\n<dd>Have no fear, help is near! There are many ways you can get back on track with Magento Store.</dd>",
          "page_layout": "2columns-right"
        },
        {
          "name": "Home page",
          "identifier": "home",
          "content": "<p>CMS homepage content goes here.</p>\r\n",
          "page_layout": "1column"
        },
        {
          "name": "Enable Cookies",
          "identifier": "enable-cookies",
          "content": "<div class=\"enable-cookies cms-content\">\r\n<p>\"Cookies\" are little pieces of data we send when you visit our store. Cookies help us get to know you better and personalize your experience. Plus they help protect you and other shoppers from fraud.</p></div>",
          "page_layout": "1column"
        },
        {
          "name": "Privacy and Cookie Policy",
          "identifier": "privacy-policy-cookie-restriction-mode",
          "content": "<div class=\"privacy-policy cms-content\">\n    <div class=\"message info\">Please replace this text with you Privacy Policy.\n Please add any additional cookies your website uses below (e.g. Google Analytics).\n        </span>\n    </div></div>",
          "page_layout": "1column"
        }
      ]
    }
  }
}

An Interesting Post about fetch CMS Blocks collection using GraphQl query, Get CMS Static block collection in GraphQL Magento 2