How to get product attribute value, label using GraphQl in Magento 2.3?

Today we can discuss about product attributes and how to get the product attributes values in Graphql. We can directly get the attribute value from native GraphQl query. We can get the custom attributes value also by passing the attribute_code to the GraphQl query.

But we have some issues when the attribute type is select box or multi-select. For select box or multi-select attributes the native GraphQl query only returns the value not the label of the value.

As far as is searched i couldn’t find a way to get the labels. So i achieved this with the custom module.I will explain here how i did it with the custom module.

So we need to create a simple module. I am not going to explain it.Apart from that we need to create shema.gaphqls file under etc directory. Resolver file under Model/Resolver directory.
A data provider file under Module/Resolver/Dataprovider directory.We are going to pass the SKU of the product and get the attributes values.

A data provider file under Module/Resolver/Dataprovider directory.We are going to pass the SKU of the product and get the attributes values.

Custom module structure
Custom module structure

schema.graphqls file

type Query {
    attributeValues (
        sku: String @doc(description: "SKU of the product")
    ): [Productdata] @resolver(class: "Ayakil\\ProductsGraphQl\\Model\\Resolver\\Productsgraphql") @doc(description: "The productdata query returns the product attributes")
}

type Productdata @doc(description: "all Attributes to show in Product Details Page") {
    atr_data : String  @doc(description: "all atributes")
}

Resolver file

<?php

namespace Ayakil\ProductsGraphQl\Model\Resolver;

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

class Productsgraphql implements ResolverInterface
{
    private $productsgraphqlDataProvider;

    /**
     * @param DataProvider\Productsgraphql $productsgraphqlDataProvider
     */
    public function __construct(
        \Ayakil\ProductsGraphQl\Model\Resolver\DataProvider\Productsgraphql $productsgraphqlDataProvider
    ) {
        $this->productsgraphqlDataProvider = $productsgraphqlDataProvider;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        //by SKU
        $sku = $this->getSku( $args);
        $productsData = $this->productsgraphqlDataProvider->getAttributesBySku( $sku );

        return $productsData;
    }

    private function getSku(array $args)
    {
        if (!isset($args['sku'])) {
            throw new GraphQlInputException(__('"SKU should be specified'));
        }
        return $args['sku'];
    }
}

Data Provider file

<?php

namespace Ayakil\ProductsGraphQl\Model\Resolver\DataProvider;

class Productsgraphql extends \Magento\Framework\View\Element\Template
{
    protected $_productRepository;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        array $data = []
        )
    {
        $this->_productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
     * @params string $sku
     * this function return all the product data by product sku
     **/
    public function getProductBySku($sku)
    {
        return $this->_productRepository->get($sku);
    }
    /**
     * @params int $id
     * this function return all the word of the day by id
     **/
    public function getAttributesBySku( $sku ){
        $_product = $this->getProductBySku($sku);
        $attributes = $_product->getAttributes();// All Product Attributes

        $attributes_data = [];
        $x=0;
        foreach ($attributes as $attribute) {
            if($attribute->getIsUserDefined()){ // Removed the system product attribute by checking the current attribute is user created
                $attributeLabel = $attribute->getFrontend()->getLabel();
                $attributeValue = $attribute->getFrontend()->getValue($_product);

                if($attribute->getAttributeCode()=="language"){
                    $attributeLabelAndValue = $attributeLabel." - ".$attributeValue;
                    $attributes_data[$x]['atr_data'] = $attributeLabelAndValue;
                }
            }
            $x++;
        }
        return $attributes_data;
    }
}

That’s it. I used if($attribute->getIsUserDefined()) to check the attribute is Custom or System attribute.
If we want to get only some attributes value and label.We can use if($attribute->getAttributeCode()==”language”) and get relevant data.For this just pass the custom attribute_code as an array and can get it.
Now lets see the GraphQl query and result.

query attributeValues{
attributeValues( sku : “24-MB02”) {
atr_data
}
}

This query will return entire custom product attributes.

product attribute value and label in graphql
sample GraphQl Request Payload and Result 

In This result Languages is the multi-select attribute and it returns the result like “Languages:- English, Tamil, Sinhala”.So in this article we write a custom GraphQl module to get the attribute value, label for products.

Attribute languages - Multi select
Attribute languages – Multi select

That’s it. Have a nice day.Enjoy coding , Learn , Experience , Teach and Help.

2 thoughts on “How to get product attribute value, label using GraphQl in Magento 2.3?”

  1. There are typos in your code.

    In resolver, you are calling getAttriNutesBySku and in DataProvider you are missing a coma in __contruct() after $productRepository 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *