Through Postman Api send data through JSON and create simple product in Magento2

  Data Written in Postman Api


[ {
    "product": {
      "productenable":1,
        "attribute_set_id": 4,
        "name": " Product new10",
        "sku": "new108",
        "price": 200.00,
        "specialprice":150,
        "special_from_date":"09/15/2017",
        "special_to_date":"09/15/2018",
        "tax_class":0,
        "quantity":100,
        "status": 1,
        "weight":10,
        "visibility":4,
        "category":{
          "0":41,
          "1":50
        },
        "manufacture_country":"Germany",
        "type_id": "simple",
     
        "productinwebsite":[1],
        "recipes":"product recipesssssss",  ///////////attributes///////////////////
        "allergene":"product recipesssss",   ///////////attributes///////////////////
        "ingredient":"product recipessss",    ///////////attributes///////////////////
        "ingredients":"product recipesss",     ///////////attributes///////////////////
        "description": "A Very Simple Product", 
        "short_description": "A Very Simple Product" 
       
       
       
       
       
    }
} ]


Controller of Magento2 to Get Post Data

[<?php
/**
 *
 * Copyright © 2015 Bluethinkcommerce. All rights reserved.
 */
namespace Bluethink\Erp\Controller\Index;

class Createproduct extends \Magento\Framework\App\Action\Action
{

/**
     * @var \Magento\Framework\App\Cache\TypeListInterface
     */
    protected $_cacheTypeList;

    /**
     * @var \Magento\Framework\App\Cache\StateInterface
     */
    protected $_cacheState;

    /**
     * @var \Magento\Framework\App\Cache\Frontend\Pool
     */
    protected $_cacheFrontendPool;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Action\Context $context
     * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList
     * @param \Magento\Framework\App\Cache\StateInterface $cacheState
     * @param \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
       \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        \Magento\Framework\App\Cache\StateInterface $cacheState,
        \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        parent::__construct($context);
        $this->_cacheTypeList = $cacheTypeList;
        $this->_cacheState = $cacheState;
        $this->_cacheFrontendPool = $cacheFrontendPool;
        $this->resultPageFactory = $resultPageFactory;
    }

    /**
     * Flush cache storage
     *
     */
    public function execute()
    {
        $data = json_decode( file_get_contents('php://input') );
        //var_dump($data);
        //echo "<pre>"; print_r($data); echo "</pre>";
       /* echo "<pre>"; print_r($data->product->category); echo "</pre>";
         echo $data->product->sku;*/
       
        //$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
        $product = $this->_objectManager->create('\Magento\Catalog\Model\Product');
        $product->setSku($data->product->sku); // Set your sku here
    /*     echo "<pre>";
         print_r($product->getData());
         */ //exit();
       
        $product->setName($data->product->name); // Name of Product
        $product->setAttributeSetId($data->product->attribute_set_id); // Attribute set id
        $product->setStatus($data->product->status); // Status on product enabled/ disabled 1/0
        $product->setWeight($data->product->weight); // weight of product
        $product->setVisibility($data->product->visibility); // visibilty of product (catalog / search / catalog, search / Not visible individually)
        $product->setTaxClassId($data->product->tax_class); // Tax class id
        $product->setTypeId($data->product->type_id); // type of product (simple/virtual/downloadable/configurable)
        $product->setPrice($data->product->price); // price of product
        $product->setCustomAttributes(array(
                'special_from_date' => $data->product->special_from_date, //special price date from
                'special_to_date' => $data->product->special_to_date, //special price date to
                'special_price' => $data->product->specialprice, //special price
            ));
     
        $product->setDescription($data->product->description);//description   
        $product->setAllergene($data->product->allergene);//attribute
        $product->setIngredient($data->product->ingredient);//attribute
        $product->setIngredients($data->product->ingredients); //attribute
        $product->setRecipes($data->product->recipes);  //attribute
        /*echo "<pre>";
         print_r($product->getData());
         */ //exit();
        $product->setShortDescription($data->product->short_description); //Short Description
        $product->setcategoryIds($data->product->category); //Categoryid
        $product->setStockData( array(
                            'use_config_manage_stock' => 0,
                            'manage_stock' => 1,
                            'is_in_stock' => 1,
                            'qty' =>$data->product->quantity
                        )); //quantity
        $product->setWebsiteIds($data->product->productinwebsite);
        //$product->setWebsiteIds($data->product->productinwebsite); //websiteid
       
                               
                         
        $product->save();
        echo "Entity Id : ====> ".$product->getEntityId();
        // Adding Image to product
        /*$imagePath = "sample.jpg"; // path of the image
        $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
        $product->save();*/
       
        // Adding Custom option to product
        /*$options = array(
                        array(
                            "sort_order"    => 1,
                            "title"         => "Custom Option 1",
                            "price_type"    => "fixed",
                            "price"         => "10",
                            "type"          => "field",
                            "is_require"   => 0
                        ),
                        array(
                            "sort_order"    => 2,
                            "title"         => "Custom Option 2",
                            "price_type"    => "fixed",
                            "price"         => "20",
                            "type"          => "field",
                            "is_require"   => 0
                        )
                    );
        foreach ($options as $arrayOption) {
            $product->setHasOptions(1);
            $product->getResource()->save($product);
            $option = $objectManager->create('\Magento\Catalog\Model\Product\Option')
                            ->setProductId($product->getId())
                            ->setStoreId($product->getStoreId())
                            ->addData($arrayOption);
            $option->save();
            $product->addOption($option);
        }*/
       
    }
}
]








Comments

Popular posts from this blog

Get Swatch Text Product id of Configurable Product in Detail Page through Jquery Magento2

Getting product Image in PHTML in Magento2

Get Customer Address with customer ID programmatically Magento2