4

I'm adding products with the following way to /rest/V1/products on Magento 2.

How can I add a product to a specific category? I'm using curl to post the data and can see the product added.

    ...

    $setHaders = array('Content-Type:application/json','Authorization:Bearer '.$adminToken);

    $productData = array(
        'sku'               => 'ZZZ simple 1  ' . uniqid(),
        'name'              => 'Simple Product ' . uniqid(),
        'visibility'        => 4, /*'catalog',*/
        'type_id'           => 'simple',
        'price'             => 99.95,
        'status'            => 1,
        'attribute_set_id'  => 4,
        'weight'            => 1,
        'custom_attributes' => array(
            array( 'attribute_code' => 'description', 'value' => 'Simple Description' ),
            array( 'attribute_code' => 'short_description', 'value' => 'Simple  Short Description' ),
            )
    );

    $productData = json_encode(array('product' => $productData));

    $requestURL = "http://192.168.1.225/rest/V1/products";


    $ch = curl_init();      
    curl_setopt($ch,CURLOPT_URL, $requestURL);

    curl_setopt($ch,CURLOPT_POSTFIELDS, $productData);

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $setHaders);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if(curl_exec($ch)===false){
        echo "Curl error: " . curl_error($ch)."\n";
    }else{
        $response = curl_exec($ch) ?: "";
    }
    curl_close($ch);

    echo $response;

    ...
12

found the answer. Here it is for anyone else interested in this problem. A product can have one or multiple categories set as follows

    $productData = array(
        'sku'               => 'ZZ-TEST-' . uniqid(),
        'name'              => 'Simple Product ' . uniqid(),
        'visibility'        => 4, /*'catalog',*/
        'type_id'           => 'simple',
        'price'             => 99.95,
        'status'            => 1,
        'attribute_set_id'  => 4,
        'weight'            => 1,
        'custom_attributes' => array(
            array( 'attribute_code' => 'category_ids', 'value' => ["42","41","32"] ),
            array( 'attribute_code' => 'description', 'value' => 'Simple Description' ),
            array( 'attribute_code' => 'short_description', 'value' => 'Simple  Short Description' ),
            )
    );
  • how to add multiple products? – prasad maganti Feb 2 '17 at 7:12
  • 2
    just make multiple REST calls – acidjunk Apr 14 '17 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.