skip to Main Content

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 🙂

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. Could you try setting “linkType” to 1 instead of “related”

    $linkTypes = ['related' => 1, 'upsell' => 4, 'crosssell' => 5, 'associated' => 3];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search