Magento 2 – Generate Product URL Key When Creating Product via Rest API

magento2productrest

I am creating Product in magento usign Rest API. Using the below format:

{
"product": {
"name": "Product Name",
"sku": "product_name_1498227094",
"attribute_set_id": "18",
"status": 1,
"visibility": 4,
"type_id": "simple",
"price": 0,
"weight": 0,
"product_links": [],
"options": [],
"tier_prices": [],
"custom_attributes": [
  {
    "attribute_code": "description",
    "value": "Product About content"
  },
  {
    "attribute_code": "short_description",
    "value": "Product Mini content"
  },
  {
    "attribute_code": "meta_title",
    "value": "Product Name"
  },
  {
    "attribute_code": "meta_keyword",
    "value": "Product Name"
  },
  {
    "attribute_code": "meta_description",
    "value": "Product Name"
  }
]
},
"saveOptions": true
}

Its creating Product first time. But If I use the same data to create product again. I am getting the below error:

[message] => URL key for specified store already exists.

As you can check, I am not passing url_key in custom_attributes array.

{
  "attribute_code": "url_key",
  "value": "10090-white-xl"
}

Here my question is: Do magento2 not create Unique URL key automatically? How can we generate Unique URL key in magento2 with consideration of SEO also ?

Best Answer

I have created a custom code to check if the URL key exists or not. As per the flow used in product import functionality in Magento 2.

public function __construct(
    --
    \Magento\Store\Model\StoreManagerInterface $storeManager, 
    \Magento\Framework\App\ResourceConnection $resource, 
    --
) {
    --
    $this->_storeManager = $storeManager;
    $this->_resource = $resource;
    --  
}



public function createUrlKey($title, $sku) 
{
    $url = preg_replace('#[^0-9a-z]+#i', '-', $title);
    $urlKey = strtolower($url);
    $storeId = (int) $this->_storeManager->getStore()->getStoreId();
    
    $isUnique = $this->checkUrlKeyDuplicates($sku, $urlKey, $storeId);
    if ($isUnique) {
        return $urlKey;
    } else {
        return $urlKey . '-' . time();
    }
}

/*
 * Function to check URL Key Duplicates in Database
 */

private function checkUrlKeyDuplicates($sku, $urlKey, $storeId) 
{
    $urlKey .= '.html';

    $connection = $this->_resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);

    $tablename = $connection->getTableName('url_rewrite');
    $sql = $connection->select()->from(
                    ['url_rewrite' => $connection->getTableName('url_rewrite')], ['request_path', 'store_id']
            )->joinLeft(
                    ['cpe' => $connection->getTableName('catalog_product_entity')], "cpe.entity_id = url_rewrite.entity_id"
            )->where('request_path IN (?)', $urlKey)
            ->where('store_id IN (?)', $storeId)
            ->where('cpe.sku not in (?)', $sku);

    $urlKeyDuplicates = $connection->fetchAssoc($sql);

    if (!empty($urlKeyDuplicates)) {
        return false;
    } else {
        return true;
    }
}
Related Topic