Magento 2: Create Group Product By Rest API

Here we are talking about to create group product by using REST API in magento2.

We assume that we have already created a simple product  and simple product’s sku are simple_api_1, simple_api_2 & simple_api_3.

Read the article of  simple product creation by click here.

<?php
/********* Create Configurable Product 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);
    $product_data= '{
	  "product": {
		"id": 0,
		"sku": "group_api_1",
		"name": "Group Api 1",
		"attributeSetId": 4,		
		"status": 1,
		"visibility": 4,
		"typeId": "grouped",
		"createdAt": "string",
		"updatedAt": "string",
		"weight": 0.5,
		"extensionAttributes": {
		  
		  "stockItem": {
			"isInStock": true        
		  }   
		  
		},    
		"productLinks": [
			{
			  "sku": "group_api_1",
			  "linkType": "associated",
			  "linkedProductSku": "simple_api_1",
			  "linkedProductType": "simple",
			  "position": 0,
			  "extensionAttributes": {
				  "qty": 5
				}
			},
			{
			  "sku": "group_api_1",
			  "linkType": "associated",
			  "linkedProductSku": "simple_api_2",
			  "linkedProductType": "simple",
			  "position": 1,
			  "extensionAttributes": {
				  "qty": 8
				}
			},
			{
			  "sku": "group_api_1",
			  "linkType": "associated",
			  "linkedProductSku": "simple_api_3",
			  "linkedProductType": "simple",
			  "position": 2,
			  "extensionAttributes": {
				  "qty": 10
				}
			}
                 ]
		
	    }
	}';


     $ch = curl_init($url."/rest/V1/products");
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS,$product_data);
     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);
	  
?>	

2 Replies to “Magento 2: Create Group Product By Rest API”

Leave a Reply

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