Magento 2 How to Update Product Using REST API?

In Magento2, we can update the existing product using REST API call. Lets have a look how we can update product by using a request URL to perform update action.

To update a product, we usually call PUT method which is an action type.

Action Type: PUT

Request URL: <base_website_url>/rest/V1/products/<sku>

We need to replace <base_website_url> and <sku> with actual website URL and product sku that needs to be updated.

For Header part of the request, we need to pass the following:
‘Content-Type:application/json’,’Authorization:Bearer ‘.$accessToken’

where $accessToken is our website access token.

<?php
$baseUrl= "http://127.0.0.1/magento2/index.php/rest";
$accessToken=  "ENTER_ACCESS_TOKEN_STRING";
$setHeaders = array('Content-Type:application/json','Authorization:Bearer '.$accessToken);
 
$url = $baseUrl."/V1/products/testsku";
$apiUrl = str_replace(" ","%20",$url);
 
$ch = curl_init();
$data = [
  "product" => [
    "visibility" => 2,
    "price" => 100,
    "custom_attributes" => [
        [
            "attribute_code" => "description",
            "value"=> "custom description"
        ]
    ]
  ]
];
 
$dataString = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $setHeaders);
$token = curl_exec($ch);
 
$response = json_decode( curl_exec($ch), TRUE);
curl_close($ch);
print_r($response);
die();

Hope this helps to update a product using above code snippet.

Leave a Reply