2

I have basic knowledge about GraphQL. Now, I would like to convert my knowledge into action. For that, I want to know about few things like how can I add my custom field to any GraphQL Query and mutations. I have also read some blog posts for this but they don't have proper guidance which I am looking for.

Can someone please explain with example of extending an existing GraphQL API for both Query and Mutations? That would be really handy.

Thanks in advance!

4
  • Do you expecting existing queries & mutation extend or creating custom queries and Mutation?
    – Mujahidh
    Commented May 18, 2020 at 8:04
  • @Mujahidh, I am expecting to extend/override existing (default magento) queries and mutations. Commented May 18, 2020 at 9:35
  • Did you check my answer for your question?
    – Mujahidh
    Commented May 22, 2020 at 4:51
  • 1
    @Mujahidh, Sorry for late response. I was busy with other stuff. I checked your detailed response. It looks fine and I think it will help me as well. I upvoted your reply. Cheers! Commented Jun 19, 2020 at 13:12

5 Answers 5

2

We can do our custom endpoints too. I have extend some existing default graphql queries.

1 . Query storeConfig -( module-store-graph-ql )

2 . Query products's ProductFilterInput - ( module-catalog-graph-ql )

1 . Query storeConfig -( module-store-graph-ql )

I extended storeConfig using following steps. create a di.xml file under module's etc/graphql directory and define the new items like below.

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\StoreGraphQl\Model\Resolver\Store\StoreConfigDataProvider">
    <arguments>
        <argument name="extendedConfigData">
<!-- Default store config sets-->
    <item name="general_store_information_name" xsi:type="string">general/store_information/name</item>
    <item name="general_store_information_additional_phone" xsi:type="string">general/store_information/additional_phone</item>
    <!-- Custom store config sets-->
    <item name="contact_us_forms_title" xsi:type="string">contact_us/forms/title</item>
    <item name="contact_us_forms_info_title" xsi:type="string">contact_us/forms/info_title</item>
    </argument>
    </arguments>
</type>
</config>

and write the schema.graphqls file

type StoreConfig {
general_store_information_name : String  @doc(description: "Store Name"),
general_store_information_phone : String  @doc(description: "Store Phone Number "),
contact_us_forms_title : String  @doc(description: "contact Us form title text"),
contact_us_forms_info_title : String  @doc(description: "contact Us information section title text")
}

After setup:upgrade and chache:clean you can run the graphql query like below to get the result.

query{
storeConfig {
    copyright
    general_store_information_name
    trans_email_ident_general_email
    contact_us_forms_title
    contact_us_forms_info_title
}
}

For better understanding read How to get the store configuration values using GraphQl in magento 2?

2 . Query products's ProductFilterInput - ( module-catalog-graph-ql ) for this section please read magento 2 graphql product query

All these customization i did based on my requirements with personally modification. It's worked out for me. Hope this will help you and some one who read this.

1

One of the possible ways of extending existing GraphQl is using the GraphQl interface. As for example, you have a new product attribute barcode now you want it in GraphQl response. In that case in your custom module's etc > schema.graphqls file add as following

interface ProductInterface {
  barcode: String @resolver (class: "Vendor\\Module\\Model\\Resolver\\ProductCustomAttribute")
}

After implementation flush the cache. You will be get your desire result.

1
  • Thanks for your reply. It is useful for interface. What about query and mutations? How can I add new fields in those type of api calls? Commented May 6, 2020 at 7:57
1

Magento 2.4

I will show you how to add custom attributes into product and customer query and mutation

1) Add custom attribute into customer query and mutation

app/code/VendoreName/ModuleName/etc

schema.graphqls

type Customer {
  sample_attribute: String @doc(description: "Customer Custom Attribute Show")
    @resolver(
      class: "\\VendoreName\\ModuleName\\Model\\Resolver\\GetCustomerCustomAttr"
    )
}

input CustomerInput {
  sample_attribute: String @doc(description: "Customer Custom Attribute Val")
}

app/code/VendoreName/ModuleName/Model/Resolver

GetCustomerCustomAttr.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare (strict_types = 1);

namespace VendoreName\ModuleName\Model\Resolver;

use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

/**
 * Customer custom attribute field resolver
 */
class GetCustomerCustomAttr implements ResolverInterface
{
    /**
     * @var Magento\Customer\Api\CustomerRepositoryInterface
     */
    protected $customerRepositoryInterface;

    /**
     * @param Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
     */
    public function __construct(
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface
    ) {
        $this->customerRepositoryInterface = $customerRepositoryInterface;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        if (!isset($value['model'])) {
            throw new LocalizedException(__('"model" value should be specified'));
        }
        /** @var CustomerInterface $customer */
        $customer = $value['model'];
        $customerId = (int) $customer->getId();
        $customerData = $this->customerRepositoryInterface->getById($customerId);

        /* Get customer custom attribute value */
        if ($customer->getCustomAttribute('sample_attributess')) {
            $customerAttributeVal = $customer->getCustomAttribute('sample_attributess')->getValue();
        } else {
            $customerAttributeVal = null;
        }

        return $customerAttributeVal;
    }
}

Run Magento Commands:

php bin/magento s:up
php bin/magento in:rein
php bin/magento s:s:d -f
php bin/magento c:c

Get customer custom attribute value

{
  customer {
    email
    sample_attribute
  }
}

Update customer custom attribute value

mutation {
  updateCustomer(
    input: {
      firstname: "Rob",
      sample_attribute: "Text"
    }
  ) {
    customer {
      firstname
      sample_attribute
    }
  }
}

2)Filter, sort, and get product custom attribute in product query

Create Custom Attribute with below options values.

enter image description here

enter image description here

app/code/VendoreName/ModuleName/etc

schema.graphqls

interface ProductInterface {
    sample_attribute: String @doc(description: "Product Custom Attribute Show")
      @resolver(
        class: "VendoreName\\ModuleName\\Model\\Resolver\\Product\\AddCustomAttribute"
      )
}

input ProductAttributeFilterInput {
  sample_attribute: FilterEqualTypeInput @doc(description: "Product Data filter with Custom Attribute Value")
}

input ProductAttributeSortInput {
  sample_attribute: SortEnum @doc(description: "Sort by the Product Custom Attribute.")
}

app/code/VendoreName/ModuleName/Model/Resolver/Product

AddCustomAttribute.php

<?php

namespace VendoreName\ModuleName\Model\Resolver\Product;

use Magento\Framework\GraphQl\Query\ResolverInterface;

/**
 * Product custom attribute field resolver
 */
class AddCustomAttribute implements ResolverInterface
{

    /**
     * @var Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;

    /**
     * @param Magento\Catalog\Model\ProductFactory $productFactory
     */
    public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productFactory = $productFactory;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        \Magento\Framework\GraphQl\Config\Element\Field $field,
        $context,
        \Magento\Framework\GraphQl\Schema\Type\ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $product = $value['model'];
        $_product = $this->productFactory->create()->load($product->getId());
        return $_product->getData('sample_attribute');
    }
}

Run Magento Commands:

php bin/magento s:up
php bin/magento in:rein
php bin/magento s:s:d -f
php bin/magento c:c

For show product custom attribute value

{
  products(filter: { sku: { eq: "24-MB01" } }) {
    items {
      name
      sku
      sample_attribute
    }
  }
}

For filter product data using custom attribute

{
  products(filter: { sample_attribute: { eq: "test" } }) {
    items {
      name
      sku
      sample_attribute
    }
  }
}

For sort product data using custom attribute

{
  products(search: "bag", sort: {sample_attribute: DESC}) {
    items {
      name
      sku
      sample_attribute
    }
  }
}
0

Is there any way to respond like storeConfig{ params{ contact_us_forms_title contact_us_forms_info_title } }

0
0

I have created extention with graphql API for feedback form with custom table with fields Name, Phone, Email, Feedback and Discliamer. This extention also sent email on data insert though API

mutation {
  createQueryFeedbacks(
    input: {
      name: "Rohit kaushik"
      mobile: "9876543210"
      email: "[email protected]"
      feedback: "This is my feedback or query to admin"
      disclaimer: "Yes"
    }
  )
  {
    feedback_submit {
      entity_id
      name
      mobile
      email
      feedback
      disclaimer
    }
  }
}

    
  

or full extenstion code you can check here https://github.com/kaushikrohit54/feedback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.