简体   繁体   中英

Assign Related Product In Magento 2 API

I am using magento 2 api for assigning product link like related or crosssell using api /V1/products/{sku}/links

Here is My Sample Code

<?php
error_reporting(E_ALL);
define('mag_apiurl',"http://www.mywebsite.com/rest/V1/");
define('tn_webshopKey',"myshowpkey");
$sku1 = "sku1";
$sku2 = "sku2";
$productData = array(
        "items" =>  array(
              "sku" => $sku1,
              "linkType" => 'related',
              "linkedProductSku" => $sku2,
              "linkedProductType" => "simple",
              "position" => 0
        )
    );

    $headers = array("Content-Type:application/json","Authorization: Bearer ".tn_webshopKey);
    $requestUrl= mag_apiurl.'products/'.$sku1.'/links';
    $ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    echo $returnProductDetails = curl_exec($ch);
?>

But Every time i run the script its response

{"message":"%fieldName is required filed.","parameters":{"fieldName":"linkType"}}

But the link type 'related' is already defined in my data (productData)

Does anyone knows the solution or related link which helps :)

Sorry Its my fault i'am reading the swagger api documentation for enterprise version of magento-2.2.* but i am working on magento-2.1.*

Actual Code Should be

$productData = array(
        "items" =>  array(
            array(           
              "sku" => $sku1,
              "link_type" => 'related',
              "linked_product_sku" => $sku2,
              "linked_product_type" => "simple",
              "position" => 0
            )  
        )
    );

    /*
    THE JOSN FORMAT START
    {
      "items": [
        {
          "sku": "string",
          "link_type": "string",
          "linked_product_sku": "string",
          "linked_product_type": "string",
          "position": 0,
          "extension_attributes": {
            "qty": 0
          }
        }
      ]
    }

 ***************END************/

There are some differences ive noticed between those documentation that each document have different model schema declaration like some has snake_case and on other hand some has camelCase so do not begin confused between the documentation of swagger and select appropriate version of document for each store

您可以尝试将“ linkType”设置为1而不是“相关”

$linkTypes = ['related' => 1, 'upsell' => 4, 'crosssell' => 5, 'associated' => 3];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM