Is it possible to add URL Rewrite rule via API call?
Hello @ivan_golubovic,
Unfortunately No !
You may need to create custom module to achieve that.
Hello @ivan_golubovic
To add URL rewrites in Magento 2 via API, you would typically need to create a custom API endpoint that can handle URL rewrites.
You need to create a custom Magento 2 module where you will define the API for creating URL rewrites.
Create the API Endpoint
efine the API routes and methods (e.g., POST) in the webapi.xml file of your custom module.
<route url="/V1/custom/urlrewrite" method="POST">
<service class="Custom\Test\Api\UrlRewriteInterface" method="createUrlRewrite"/>
<resources>
<resource ref="anonymous"/>
</resources>
</route>Create the URL Rewrite Logic:you can use Magento’s \Magento\UrlRewrite\Model\UrlRewriteFactory class to programmatically create URL rewrites.
namespace Custom\Test\Model; use Magento\UrlRewrite\Model\UrlRewriteFactory; use Magento\Store\Model\StoreManagerInterface;
class UrlRewriteManager { protected $urlRewriteFactory; protected $storeManager; public function __construct( UrlRewriteFactory $urlRewriteFactory, StoreManagerInterface $storeManager ) { $this->urlRewriteFactory = $urlRewriteFactory; $this->storeManager = $storeManager; } public function createUrlRewrite($requestPath, $targetPath) { $storeId = $this->storeManager->getStore()->getId(); $urlRewrite = $this->urlRewriteFactory->create(); $urlRewrite->setStoreId($storeId); $urlRewrite->setRequestPath($requestPath); $urlRewrite->setTargetPath($targetPath); $urlRewrite->setIsSystem(0); // 1 for system-generated, 0 for custom try { $urlRewrite->save(); return true; } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException( __('Error saving URL rewrite: %1', $e->getMessage()) ); } } }
namespace Custom\Test\Api;
interface UrlRewriteInterface
{
/**
* Create URL Rewrite
*
* @param string $requestPath
* @param string $targetPath
* @return bool
*/
public function createUrlRewrite($requestPath, $targetPath);
}Testing Your Custom API:
curl -X POST "https://your-magento-site.com/rest/V1/custom/urlrewrite" \
-H "Content-Type: application/json" \
-d '{
"requestPath": "custom-url-path",
"targetPath": "catalog/product/view/id/123"
}'This will create a URL rewrite rule from custom-url-path to catalog/product/view/id/123
Hope it helps !
If you find our reply helpful, please give us kudos.
A Leading Magento Development Agency That Delivers Powerful Results, Innovation, and Secure Digital Transformation.
WebDesk Solution Support Team
Get a Free Quote | | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789
Thank You,
WebDesk Solution Support Team
Get a Free Quote | Email | Adobe Commerce Partner | Hire Us | Call Us 877.536.3789
Location: 150 King St. W. Toronto, ON M5H 1J9