Magento – REST API creating more than one media entry for product

apimagento2rest

I am trying to import some images for some products using rest rest API (POST to /V1/products/{sku}/media). Works fine for the first image for each product but always fails for the second with the following message:

Failed to save new media gallery entry." which tells me nothing.

I have checked the payload many times and the few fields that could possibly require unique values (label, position and content name) are all set to unique ones.

What am I missing?

Best Answer

I spend lot of time to understand ... I had same problem. On development my java application, using official API, first i create product with one (main image), after I trying to add more images with Your error. Solution is VERY SIMPLE. When You add more than one image, avoid to add ID in json call. (I have my own Java model which reproduce original API and NEVER use "int" => use "Integer" instead, for all keys at model) BAD:

{
  "entry": {
      "id": 0,
      "mediaType": "image",
      "position": 0,
      "disabled": false,
      "types": ["image", "small_image", "thumbnail"],
      "content":{
        "base64_encoded_data" : "_9j_4AAQSkZJRgABAQEAYABgAAD__...<cutted_here>",
        "type": "image/jpeg",
        "name":"pic_name.jpg"
    }
  }
}

Right way:

{
  "entry": {
      "mediaType": "image",
      "position": 0,
      "disabled": false,
      "types": ["image", "small_image", "thumbnail"],
      "content":{
        "base64_encoded_data" : "_9j_4AAQSkZJRgABAQEAYABgAAD__...<cutted_here>",
        "type": "image/jpeg",
        "name":"pic_name.jpg"
    }
  }
}

When You read official documentation is NO describe to right way. I've founded solution looking here: line 509, see : if (isset($entry['id'])) at ./vendor/magento/module-catalog/Model/ProductRepository.php

PHP is looking if ID is set !!!

Alberto

Related Topic