Magento 2: Create Product Custom Options By Rest API

In this post, We can easily create product custom options by REST API.

Here we are creating custom options of a product and type of custom option is drop-down.

We can create text, multi-select type custom options.
Type  => value of custom option type are given below:

‘Text’ => ‘field’
‘Drop-down’=> ‘drop_down’
‘Multi-select’=>’multiple’
we can use these value as type of options.

 

<?php
/********* Create Product Custom Options By Rest API *********/
try {
    $url = “http://magento2.local.com”;
    $api_username = ‘api_user’;
    $api_password = ‘apipass@456’;
    $userData = array("username" => $api_username, "password" => $api_password);


    $ch = curl_init($url."/rest/V1/integration/admin/token");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

    $token = curl_exec($ch);
    $custom_option = '{
        "option": {
        "productSku": "24-WB04",
        "optionId": 0,
        "title": "Material",
        "type": "drop_down",
        "sortOrder": 0,
        "isRequire": false,
        "price": 0,
        "priceType": "fixed",
        "sku": "",    
        "values": [
           {
           "title": "Leather",
           "sortOrder": 0,
           "price": 0,
           "priceType": "fixed",
           "sku": ""        
          },
         {
          "title": "Rexinene",
          "sortOrder": 0,
          "price": 0,
          "priceType": "fixed",
          "sku": ""        
         },
         {
          "title": "Bata",
          "sortOrder": 0,
          "price": 0,
          "priceType": "fixed",
          "sku": ""        
         }
       ],
      "extensionAttributes": {}
      }
    }';


     $ch = curl_init($url."/rest/V1/products/options");
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS,$custom_option);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

     $result = curl_exec($ch);
     }catch(Exception $e){
		 
           echo $e->getMessage();
           
     }
      
     /****** Show results ****/ 
	  var_dump($result);
	  
?>

 

Leave a Reply

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