How to get Product Attribute Code by attribute id Magento 2?

You can retrieve the Product/Category Attribute code value by the id in Magento 2.

You are developing feature and you required to fetch attribute code value by the attribute id, in this scenario, this article will be helpful.

Let’s take an example, Native Magento With Sample Data, Color Attribute id is the 93 and you need to get Color code value dynamically(color), You can retrieve the code by the below snippets of code,

namespace Jesadiya\AttributeCode\Model;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;

class AttributeCode
     * @var ProductAttributeRepositoryInterface
    private $attributeRepository;

    public function __construct(
        ProductAttributeRepositoryInterface $attributeRepository
    ) {
        $this->attributeRepository = $attributeRepository;

     * Get Attribute Code by attribute id
     * @param int $id
     * @return string
     * @throws NoSuchEntityException
    public function getAttributeCodeById(int $id)
        return $this->attributeRepository->get($id)->getAttributeCode();

Method calls from the template or PHP class,
$id = 93;
echo $attributeCode = $this->getAttributeCodeById($id);