Magento 2 API – Assign Related Product

magento2magento2-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)

Can anyone knows the solution

Best Answer

Looking at the Swagger Documentation should these not be -

{
  "items": [
    {
      "sku": "string",
      "link_type": "string",
      "linked_product_sku": "string",
      "linked_product_type": "string",
      "position": 0,
    }
  ]
}

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

Related Topic