How to add product image when creating via rest api?Get multiple product images using REST APIHow to display...

Does a druid starting with a bow start with no arrows?

Arrow those variables!

How is it possible to have an ability score that is less than 3?

Can I ask the recruiters in my resume to put the reason why I am rejected?

Did Shadowfax go to Valinor?

Emailing HOD to enhance faculty application

I'm flying to France today and my passport expires in less than 2 months

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Is the Joker left-handed?

When a company launches a new product do they "come out" with a new product or do they "come up" with a new product?

Alternative to sending password over mail?

Took a trip to a parallel universe, need help deciphering

AES: Why is it a good practice to use only the first 16bytes of a hash for encryption?

Why does Kotter return in Welcome Back Kotter

Assassin's bullet with mercury

What is the most common color to indicate the input-field is disabled?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Brothers & sisters

How to prevent "they're falling in love" trope

Fully-Firstable Anagram Sets

What mechanic is there to disable a threat instead of killing it?

In Romance of the Three Kingdoms why do people still use bamboo sticks when papers are already invented?

1960's book about a plague that kills all white people

Why is consensus so controversial in Britain?



How to add product image when creating via rest api?


Get multiple product images using REST APIHow to display the image, name and short description for a bundle product itemsAdd an image to a product description in 1.8.1How can I get product list with its detail in rest API I'm on magento2Set default product image via REST APICustom Sort order for magento product collection (Sort collection by an array values)How to Update Products Details using sku in magento 2Magento 2 - How to retrieve the name and quantity for each product ordered in success.phtml fileHow to get product quantity by using REST API product filterHow to Update Magento 2 configurable child products price by REST APIHow to remove SKU from product name in search results?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







3















This is how I creating product.



{
"product": {
"attribute_set_id": 4,
"type_id": "simple",
"sku": "B201-SKU",
"name": "B201",
"price": 25,
"status": 1,
"custom_attributes": {
"description": "Heavy Duty Brake Cables",
"meta_description": "Some describing text"
}
}
}









share|improve this question





























    3















    This is how I creating product.



    {
    "product": {
    "attribute_set_id": 4,
    "type_id": "simple",
    "sku": "B201-SKU",
    "name": "B201",
    "price": 25,
    "status": 1,
    "custom_attributes": {
    "description": "Heavy Duty Brake Cables",
    "meta_description": "Some describing text"
    }
    }
    }









    share|improve this question

























      3












      3








      3








      This is how I creating product.



      {
      "product": {
      "attribute_set_id": 4,
      "type_id": "simple",
      "sku": "B201-SKU",
      "name": "B201",
      "price": 25,
      "status": 1,
      "custom_attributes": {
      "description": "Heavy Duty Brake Cables",
      "meta_description": "Some describing text"
      }
      }
      }









      share|improve this question














      This is how I creating product.



      {
      "product": {
      "attribute_set_id": 4,
      "type_id": "simple",
      "sku": "B201-SKU",
      "name": "B201",
      "price": 25,
      "status": 1,
      "custom_attributes": {
      "description": "Heavy Duty Brake Cables",
      "meta_description": "Some describing text"
      }
      }
      }






      magento2 product-images






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Sep 19 '16 at 11:44









      iamkdeviamkdev

      178316




      178316






















          3 Answers
          3






          active

          oldest

          votes


















          3














          You need an additional POST with the route :



          http://YOUR_MAGENTO_ADDRESS/index.php/rest/V1/products/B201-SKU/media



          The basic template JSON would be something like:



          {
          "entry": {
          "media_type": "image",
          "label": "Image",
          "position": 1,
          "disabled": false,
          "types": [
          "image",
          "small_image",
          "thumbnail"
          ],
          "content": {
          "base64EncodedData": YOU_NEED_YOUR_IMAGE_BASE64_ENCODED,
          "type": "image/png",
          "name": "choose_any_name.png"
          }
          }
          }


          After that your previously added product B201-SKU, will have the associated image.






          share|improve this answer
























          • You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

            – MFAL
            Aug 11 '17 at 9:57











          • Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

            – James Harrington
            Oct 4 '17 at 0:54











          • According to the docs, base64EncodedData should actually be base64_encoded_data.

            – Luke Cousins
            Nov 25 '17 at 9:19



















          0














          We need to add add these attributes: image, small_image and thumbnail to custom_attributes:



          $productData = [
          "attribute_set_id" => 4,
          "type_id": "simple",
          "sku": "B201-SKU",
          "name": "B201",
          "price": 25,
          "status": 1,
          "custom_attributes" => [
          ["attribute_code" => "description", "value" => "Heavy Duty Brake Cables"],
          ["attribute_code" => "meta_description", "value" => "Some describing text"],
          ["attribute_code" => "image", "value" => "/w/i/sample_1.jpg"],
          ["attribute_code" => "small_image", "value" => "/w/i/sample_2.jpg"],
          ["attribute_code" => "thumbnail", "value" => "/w/i/sample_2.jpg"]

          ]
          ];


          Payload:



          {
          "product": {
          "attribute_set_id": 4,
          "type_id": "simple",
          "sku": "B201-SKU",
          "name": "B201",
          "price": 25,
          "status": 1,
          "custom_attributes": {
          "description": "Heavy Duty Brake Cables",
          "meta_description": "Some describing text",
          "image" : "/w/i/sample_1.jpg",
          "small_image": "/w/i/sample_2.jpg",
          "thumbnail": "/w/i/sample_3.jpg"
          }
          }
          }


          Read more here.






          share|improve this answer


























          • I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

            – iamkdev
            Sep 20 '16 at 6:50













          • We need to upload to Magento. These images are under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 7:23











          • How these images will be there before upload?

            – iamkdev
            Sep 20 '16 at 7:43











          • Like import process, we need to upload these images with the path under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 16:14











          • I want to upload images via rest api into magento but this is not doing that?

            – iamkdev
            Sep 21 '16 at 7:01



















          0














          For uploading and assigning images to products via API, there are two different scenarios:



          A) each image is used for exactly one SKU

          B) images can be used for multiple SKUs



          In case A, things are simple, and @mfal 's answer in this post gives enough clues to get the job done:



          Create a post to https://<magento>/rest/V1/products/<sku>/media (remember to url encode the sku) - with a body like this:



          {
          "entry": {
          "media_type": "image",
          "label": "I am an image!",
          "types": [
          "image"
          ],
          "content": {
          {
          "base64_encoded_data": <base64 encoded file>,
          "type": "image/jpeg",
          "name": "<image filename>"
          }
          },
          "file": "<image filename>"
          }
          }


          ... the image is uploaded to Magento, added to the table catalog_product_entity_media_gallery, and linked to the product. I have attached a python script for this type of request at the end of this answer.



          Unfortunately, this happens with every call of the API: the picture is uploaded again and again. Magento2 detects that a file with the same name exists already and adds an incrementor to the file name (file.jpg, file_1.jpg, file_2.jpg, ...). Such an easy way to write the harddisk full!



          This is, why in case B, things necessarily should get a bit more complex. Case B applies to situations where the script is to be executed multiple times, maybe for automation purposes. It also applies to situations where one picture is to be used for multiple skus, as in a clothes shop, where typically all sizes of the same product have different skus, but the same image.



          The entry post to https://<magento>/rest/V1/products/<sku>/media is still a great starting point, but we need to check in advance, if the file exists on the server yet.



          While it is quite easy to figure out which images are linked to a certain sku by using the API, I did not find a quick way to figure out if an image exists on the server. Therefore, an image uploading script might need to maintain a list of uploaded filenames. It could be based on the content of the table catalog_product_entity_media_gallery.



          In cases where an image exists on the server already, we only need to assign it to the product / sku. This is done via a different API call. Assuming the product has been created already, the API call would go as a PUT request to https://magento/rest/V1/products/10000%2F100%2FS:



          {
          "product": {
          "custom_attributes": {
          "image" : "<filename of the image in catalog_product_entity_media_gallery>",
          "thumbnail" : "<filename of the image in catalog_product_entity_media_gallery>",
          "small_image" : "<filename of the image in catalog_product_entity_media_gallery>"
          },
          "media_gallery_entries": [
          {
          "id": <value id of the image in catalog_product_entity_media_gallery> ,
          "media_type": "image",
          "label": "<choose an image label>",
          "position": 1,
          "disabled": true,
          "types": [
          "thumbnail"
          ],
          "file": "<filename of the image in catalog_product_entity_media_gallery>"
          }
          ]
          }
          }


          This assigns a picture, - exactly one picture to the product, and removes all other ones. We therefore need to ensure that we create one media_gallery_entry per existing image, before we send this API request.





          Here is a python3 script that uploads one image to one sku; mainly for case A:



          import requests
          import base64
          import urllib
          from json import dumps

          TOKEN='123123123123123123123123'
          IMGFILENAME='my_image_file.jpg'
          SKU='10000/100/S'
          DOMAIN='https://my-magento-domain.com'

          with open(IMGFILENAME, "rb") as image_file:
          b64_encoded_string = base64.b64encode(image_file.read()).decode("utf8")
          raw_data = {'base64_encoded_data': b64_encoded_string, 'type': 'image/jpeg', 'name': IMGFILENAME}
          json_data = dumps(raw_data, indent=2)

          url = DOMAIN + '/rest/V1/products/' + urllib.parse.quote_plus(SKU) + '/media'

          mystring = f'''
          {{
          "entry": {{
          "media_type": "image",
          "label": "my image label",
          "types": [
          "image"
          ],
          "content":
          {json_data}
          ,
          "file": "{IMGFILENAME}"
          }}
          }}
          '''

          headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
          response = requests.post(url, data=mystring, headers=headers)
          print("Response:n" + response.text + "nRequest Headers:" + response.request.headers + "nResponse Headers:" + response.headers)




          share
























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "479"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f137038%2fhow-to-add-product-image-when-creating-via-rest-api%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            You need an additional POST with the route :



            http://YOUR_MAGENTO_ADDRESS/index.php/rest/V1/products/B201-SKU/media



            The basic template JSON would be something like:



            {
            "entry": {
            "media_type": "image",
            "label": "Image",
            "position": 1,
            "disabled": false,
            "types": [
            "image",
            "small_image",
            "thumbnail"
            ],
            "content": {
            "base64EncodedData": YOU_NEED_YOUR_IMAGE_BASE64_ENCODED,
            "type": "image/png",
            "name": "choose_any_name.png"
            }
            }
            }


            After that your previously added product B201-SKU, will have the associated image.






            share|improve this answer
























            • You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

              – MFAL
              Aug 11 '17 at 9:57











            • Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

              – James Harrington
              Oct 4 '17 at 0:54











            • According to the docs, base64EncodedData should actually be base64_encoded_data.

              – Luke Cousins
              Nov 25 '17 at 9:19
















            3














            You need an additional POST with the route :



            http://YOUR_MAGENTO_ADDRESS/index.php/rest/V1/products/B201-SKU/media



            The basic template JSON would be something like:



            {
            "entry": {
            "media_type": "image",
            "label": "Image",
            "position": 1,
            "disabled": false,
            "types": [
            "image",
            "small_image",
            "thumbnail"
            ],
            "content": {
            "base64EncodedData": YOU_NEED_YOUR_IMAGE_BASE64_ENCODED,
            "type": "image/png",
            "name": "choose_any_name.png"
            }
            }
            }


            After that your previously added product B201-SKU, will have the associated image.






            share|improve this answer
























            • You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

              – MFAL
              Aug 11 '17 at 9:57











            • Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

              – James Harrington
              Oct 4 '17 at 0:54











            • According to the docs, base64EncodedData should actually be base64_encoded_data.

              – Luke Cousins
              Nov 25 '17 at 9:19














            3












            3








            3







            You need an additional POST with the route :



            http://YOUR_MAGENTO_ADDRESS/index.php/rest/V1/products/B201-SKU/media



            The basic template JSON would be something like:



            {
            "entry": {
            "media_type": "image",
            "label": "Image",
            "position": 1,
            "disabled": false,
            "types": [
            "image",
            "small_image",
            "thumbnail"
            ],
            "content": {
            "base64EncodedData": YOU_NEED_YOUR_IMAGE_BASE64_ENCODED,
            "type": "image/png",
            "name": "choose_any_name.png"
            }
            }
            }


            After that your previously added product B201-SKU, will have the associated image.






            share|improve this answer













            You need an additional POST with the route :



            http://YOUR_MAGENTO_ADDRESS/index.php/rest/V1/products/B201-SKU/media



            The basic template JSON would be something like:



            {
            "entry": {
            "media_type": "image",
            "label": "Image",
            "position": 1,
            "disabled": false,
            "types": [
            "image",
            "small_image",
            "thumbnail"
            ],
            "content": {
            "base64EncodedData": YOU_NEED_YOUR_IMAGE_BASE64_ENCODED,
            "type": "image/png",
            "name": "choose_any_name.png"
            }
            }
            }


            After that your previously added product B201-SKU, will have the associated image.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 11 '17 at 9:53









            MFALMFAL

            1316




            1316













            • You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

              – MFAL
              Aug 11 '17 at 9:57











            • Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

              – James Harrington
              Oct 4 '17 at 0:54











            • According to the docs, base64EncodedData should actually be base64_encoded_data.

              – Luke Cousins
              Nov 25 '17 at 9:19



















            • You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

              – MFAL
              Aug 11 '17 at 9:57











            • Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

              – James Harrington
              Oct 4 '17 at 0:54











            • According to the docs, base64EncodedData should actually be base64_encoded_data.

              – Luke Cousins
              Nov 25 '17 at 9:19

















            You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

            – MFAL
            Aug 11 '17 at 9:57





            You can also check the catalogProductAttributeMediaGalleryManagementV1 for further options and instructions in the Magento2 online Rest API documentation

            – MFAL
            Aug 11 '17 at 9:57













            Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

            – James Harrington
            Oct 4 '17 at 0:54





            Just heads up. When converting an image to base64 most online converters will put the meta-data at the beginning like data/jpeg. Everything before the comma needs to be stripped for Magento.

            – James Harrington
            Oct 4 '17 at 0:54













            According to the docs, base64EncodedData should actually be base64_encoded_data.

            – Luke Cousins
            Nov 25 '17 at 9:19





            According to the docs, base64EncodedData should actually be base64_encoded_data.

            – Luke Cousins
            Nov 25 '17 at 9:19













            0














            We need to add add these attributes: image, small_image and thumbnail to custom_attributes:



            $productData = [
            "attribute_set_id" => 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes" => [
            ["attribute_code" => "description", "value" => "Heavy Duty Brake Cables"],
            ["attribute_code" => "meta_description", "value" => "Some describing text"],
            ["attribute_code" => "image", "value" => "/w/i/sample_1.jpg"],
            ["attribute_code" => "small_image", "value" => "/w/i/sample_2.jpg"],
            ["attribute_code" => "thumbnail", "value" => "/w/i/sample_2.jpg"]

            ]
            ];


            Payload:



            {
            "product": {
            "attribute_set_id": 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes": {
            "description": "Heavy Duty Brake Cables",
            "meta_description": "Some describing text",
            "image" : "/w/i/sample_1.jpg",
            "small_image": "/w/i/sample_2.jpg",
            "thumbnail": "/w/i/sample_3.jpg"
            }
            }
            }


            Read more here.






            share|improve this answer


























            • I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

              – iamkdev
              Sep 20 '16 at 6:50













            • We need to upload to Magento. These images are under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 7:23











            • How these images will be there before upload?

              – iamkdev
              Sep 20 '16 at 7:43











            • Like import process, we need to upload these images with the path under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 16:14











            • I want to upload images via rest api into magento but this is not doing that?

              – iamkdev
              Sep 21 '16 at 7:01
















            0














            We need to add add these attributes: image, small_image and thumbnail to custom_attributes:



            $productData = [
            "attribute_set_id" => 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes" => [
            ["attribute_code" => "description", "value" => "Heavy Duty Brake Cables"],
            ["attribute_code" => "meta_description", "value" => "Some describing text"],
            ["attribute_code" => "image", "value" => "/w/i/sample_1.jpg"],
            ["attribute_code" => "small_image", "value" => "/w/i/sample_2.jpg"],
            ["attribute_code" => "thumbnail", "value" => "/w/i/sample_2.jpg"]

            ]
            ];


            Payload:



            {
            "product": {
            "attribute_set_id": 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes": {
            "description": "Heavy Duty Brake Cables",
            "meta_description": "Some describing text",
            "image" : "/w/i/sample_1.jpg",
            "small_image": "/w/i/sample_2.jpg",
            "thumbnail": "/w/i/sample_3.jpg"
            }
            }
            }


            Read more here.






            share|improve this answer


























            • I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

              – iamkdev
              Sep 20 '16 at 6:50













            • We need to upload to Magento. These images are under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 7:23











            • How these images will be there before upload?

              – iamkdev
              Sep 20 '16 at 7:43











            • Like import process, we need to upload these images with the path under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 16:14











            • I want to upload images via rest api into magento but this is not doing that?

              – iamkdev
              Sep 21 '16 at 7:01














            0












            0








            0







            We need to add add these attributes: image, small_image and thumbnail to custom_attributes:



            $productData = [
            "attribute_set_id" => 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes" => [
            ["attribute_code" => "description", "value" => "Heavy Duty Brake Cables"],
            ["attribute_code" => "meta_description", "value" => "Some describing text"],
            ["attribute_code" => "image", "value" => "/w/i/sample_1.jpg"],
            ["attribute_code" => "small_image", "value" => "/w/i/sample_2.jpg"],
            ["attribute_code" => "thumbnail", "value" => "/w/i/sample_2.jpg"]

            ]
            ];


            Payload:



            {
            "product": {
            "attribute_set_id": 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes": {
            "description": "Heavy Duty Brake Cables",
            "meta_description": "Some describing text",
            "image" : "/w/i/sample_1.jpg",
            "small_image": "/w/i/sample_2.jpg",
            "thumbnail": "/w/i/sample_3.jpg"
            }
            }
            }


            Read more here.






            share|improve this answer















            We need to add add these attributes: image, small_image and thumbnail to custom_attributes:



            $productData = [
            "attribute_set_id" => 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes" => [
            ["attribute_code" => "description", "value" => "Heavy Duty Brake Cables"],
            ["attribute_code" => "meta_description", "value" => "Some describing text"],
            ["attribute_code" => "image", "value" => "/w/i/sample_1.jpg"],
            ["attribute_code" => "small_image", "value" => "/w/i/sample_2.jpg"],
            ["attribute_code" => "thumbnail", "value" => "/w/i/sample_2.jpg"]

            ]
            ];


            Payload:



            {
            "product": {
            "attribute_set_id": 4,
            "type_id": "simple",
            "sku": "B201-SKU",
            "name": "B201",
            "price": 25,
            "status": 1,
            "custom_attributes": {
            "description": "Heavy Duty Brake Cables",
            "meta_description": "Some describing text",
            "image" : "/w/i/sample_1.jpg",
            "small_image": "/w/i/sample_2.jpg",
            "thumbnail": "/w/i/sample_3.jpg"
            }
            }
            }


            Read more here.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 13 '17 at 12:55









            Community

            1




            1










            answered Sep 19 '16 at 12:29









            Khoa TruongDinhKhoa TruongDinh

            22k64187




            22k64187













            • I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

              – iamkdev
              Sep 20 '16 at 6:50













            • We need to upload to Magento. These images are under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 7:23











            • How these images will be there before upload?

              – iamkdev
              Sep 20 '16 at 7:43











            • Like import process, we need to upload these images with the path under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 16:14











            • I want to upload images via rest api into magento but this is not doing that?

              – iamkdev
              Sep 21 '16 at 7:01



















            • I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

              – iamkdev
              Sep 20 '16 at 6:50













            • We need to upload to Magento. These images are under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 7:23











            • How these images will be there before upload?

              – iamkdev
              Sep 20 '16 at 7:43











            • Like import process, we need to upload these images with the path under pub/media/catalog/product.

              – Khoa TruongDinh
              Sep 20 '16 at 16:14











            • I want to upload images via rest api into magento but this is not doing that?

              – iamkdev
              Sep 21 '16 at 7:01

















            I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

            – iamkdev
            Sep 20 '16 at 6:50







            I tried like this but the image is not uploaded. And why the path is /w/i/sample_1.jpg ? The image may be in my /home/images/ from here I want to upload to magento. or may be in base64.

            – iamkdev
            Sep 20 '16 at 6:50















            We need to upload to Magento. These images are under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 7:23





            We need to upload to Magento. These images are under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 7:23













            How these images will be there before upload?

            – iamkdev
            Sep 20 '16 at 7:43





            How these images will be there before upload?

            – iamkdev
            Sep 20 '16 at 7:43













            Like import process, we need to upload these images with the path under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 16:14





            Like import process, we need to upload these images with the path under pub/media/catalog/product.

            – Khoa TruongDinh
            Sep 20 '16 at 16:14













            I want to upload images via rest api into magento but this is not doing that?

            – iamkdev
            Sep 21 '16 at 7:01





            I want to upload images via rest api into magento but this is not doing that?

            – iamkdev
            Sep 21 '16 at 7:01











            0














            For uploading and assigning images to products via API, there are two different scenarios:



            A) each image is used for exactly one SKU

            B) images can be used for multiple SKUs



            In case A, things are simple, and @mfal 's answer in this post gives enough clues to get the job done:



            Create a post to https://<magento>/rest/V1/products/<sku>/media (remember to url encode the sku) - with a body like this:



            {
            "entry": {
            "media_type": "image",
            "label": "I am an image!",
            "types": [
            "image"
            ],
            "content": {
            {
            "base64_encoded_data": <base64 encoded file>,
            "type": "image/jpeg",
            "name": "<image filename>"
            }
            },
            "file": "<image filename>"
            }
            }


            ... the image is uploaded to Magento, added to the table catalog_product_entity_media_gallery, and linked to the product. I have attached a python script for this type of request at the end of this answer.



            Unfortunately, this happens with every call of the API: the picture is uploaded again and again. Magento2 detects that a file with the same name exists already and adds an incrementor to the file name (file.jpg, file_1.jpg, file_2.jpg, ...). Such an easy way to write the harddisk full!



            This is, why in case B, things necessarily should get a bit more complex. Case B applies to situations where the script is to be executed multiple times, maybe for automation purposes. It also applies to situations where one picture is to be used for multiple skus, as in a clothes shop, where typically all sizes of the same product have different skus, but the same image.



            The entry post to https://<magento>/rest/V1/products/<sku>/media is still a great starting point, but we need to check in advance, if the file exists on the server yet.



            While it is quite easy to figure out which images are linked to a certain sku by using the API, I did not find a quick way to figure out if an image exists on the server. Therefore, an image uploading script might need to maintain a list of uploaded filenames. It could be based on the content of the table catalog_product_entity_media_gallery.



            In cases where an image exists on the server already, we only need to assign it to the product / sku. This is done via a different API call. Assuming the product has been created already, the API call would go as a PUT request to https://magento/rest/V1/products/10000%2F100%2FS:



            {
            "product": {
            "custom_attributes": {
            "image" : "<filename of the image in catalog_product_entity_media_gallery>",
            "thumbnail" : "<filename of the image in catalog_product_entity_media_gallery>",
            "small_image" : "<filename of the image in catalog_product_entity_media_gallery>"
            },
            "media_gallery_entries": [
            {
            "id": <value id of the image in catalog_product_entity_media_gallery> ,
            "media_type": "image",
            "label": "<choose an image label>",
            "position": 1,
            "disabled": true,
            "types": [
            "thumbnail"
            ],
            "file": "<filename of the image in catalog_product_entity_media_gallery>"
            }
            ]
            }
            }


            This assigns a picture, - exactly one picture to the product, and removes all other ones. We therefore need to ensure that we create one media_gallery_entry per existing image, before we send this API request.





            Here is a python3 script that uploads one image to one sku; mainly for case A:



            import requests
            import base64
            import urllib
            from json import dumps

            TOKEN='123123123123123123123123'
            IMGFILENAME='my_image_file.jpg'
            SKU='10000/100/S'
            DOMAIN='https://my-magento-domain.com'

            with open(IMGFILENAME, "rb") as image_file:
            b64_encoded_string = base64.b64encode(image_file.read()).decode("utf8")
            raw_data = {'base64_encoded_data': b64_encoded_string, 'type': 'image/jpeg', 'name': IMGFILENAME}
            json_data = dumps(raw_data, indent=2)

            url = DOMAIN + '/rest/V1/products/' + urllib.parse.quote_plus(SKU) + '/media'

            mystring = f'''
            {{
            "entry": {{
            "media_type": "image",
            "label": "my image label",
            "types": [
            "image"
            ],
            "content":
            {json_data}
            ,
            "file": "{IMGFILENAME}"
            }}
            }}
            '''

            headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
            response = requests.post(url, data=mystring, headers=headers)
            print("Response:n" + response.text + "nRequest Headers:" + response.request.headers + "nResponse Headers:" + response.headers)




            share




























              0














              For uploading and assigning images to products via API, there are two different scenarios:



              A) each image is used for exactly one SKU

              B) images can be used for multiple SKUs



              In case A, things are simple, and @mfal 's answer in this post gives enough clues to get the job done:



              Create a post to https://<magento>/rest/V1/products/<sku>/media (remember to url encode the sku) - with a body like this:



              {
              "entry": {
              "media_type": "image",
              "label": "I am an image!",
              "types": [
              "image"
              ],
              "content": {
              {
              "base64_encoded_data": <base64 encoded file>,
              "type": "image/jpeg",
              "name": "<image filename>"
              }
              },
              "file": "<image filename>"
              }
              }


              ... the image is uploaded to Magento, added to the table catalog_product_entity_media_gallery, and linked to the product. I have attached a python script for this type of request at the end of this answer.



              Unfortunately, this happens with every call of the API: the picture is uploaded again and again. Magento2 detects that a file with the same name exists already and adds an incrementor to the file name (file.jpg, file_1.jpg, file_2.jpg, ...). Such an easy way to write the harddisk full!



              This is, why in case B, things necessarily should get a bit more complex. Case B applies to situations where the script is to be executed multiple times, maybe for automation purposes. It also applies to situations where one picture is to be used for multiple skus, as in a clothes shop, where typically all sizes of the same product have different skus, but the same image.



              The entry post to https://<magento>/rest/V1/products/<sku>/media is still a great starting point, but we need to check in advance, if the file exists on the server yet.



              While it is quite easy to figure out which images are linked to a certain sku by using the API, I did not find a quick way to figure out if an image exists on the server. Therefore, an image uploading script might need to maintain a list of uploaded filenames. It could be based on the content of the table catalog_product_entity_media_gallery.



              In cases where an image exists on the server already, we only need to assign it to the product / sku. This is done via a different API call. Assuming the product has been created already, the API call would go as a PUT request to https://magento/rest/V1/products/10000%2F100%2FS:



              {
              "product": {
              "custom_attributes": {
              "image" : "<filename of the image in catalog_product_entity_media_gallery>",
              "thumbnail" : "<filename of the image in catalog_product_entity_media_gallery>",
              "small_image" : "<filename of the image in catalog_product_entity_media_gallery>"
              },
              "media_gallery_entries": [
              {
              "id": <value id of the image in catalog_product_entity_media_gallery> ,
              "media_type": "image",
              "label": "<choose an image label>",
              "position": 1,
              "disabled": true,
              "types": [
              "thumbnail"
              ],
              "file": "<filename of the image in catalog_product_entity_media_gallery>"
              }
              ]
              }
              }


              This assigns a picture, - exactly one picture to the product, and removes all other ones. We therefore need to ensure that we create one media_gallery_entry per existing image, before we send this API request.





              Here is a python3 script that uploads one image to one sku; mainly for case A:



              import requests
              import base64
              import urllib
              from json import dumps

              TOKEN='123123123123123123123123'
              IMGFILENAME='my_image_file.jpg'
              SKU='10000/100/S'
              DOMAIN='https://my-magento-domain.com'

              with open(IMGFILENAME, "rb") as image_file:
              b64_encoded_string = base64.b64encode(image_file.read()).decode("utf8")
              raw_data = {'base64_encoded_data': b64_encoded_string, 'type': 'image/jpeg', 'name': IMGFILENAME}
              json_data = dumps(raw_data, indent=2)

              url = DOMAIN + '/rest/V1/products/' + urllib.parse.quote_plus(SKU) + '/media'

              mystring = f'''
              {{
              "entry": {{
              "media_type": "image",
              "label": "my image label",
              "types": [
              "image"
              ],
              "content":
              {json_data}
              ,
              "file": "{IMGFILENAME}"
              }}
              }}
              '''

              headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
              response = requests.post(url, data=mystring, headers=headers)
              print("Response:n" + response.text + "nRequest Headers:" + response.request.headers + "nResponse Headers:" + response.headers)




              share


























                0












                0








                0







                For uploading and assigning images to products via API, there are two different scenarios:



                A) each image is used for exactly one SKU

                B) images can be used for multiple SKUs



                In case A, things are simple, and @mfal 's answer in this post gives enough clues to get the job done:



                Create a post to https://<magento>/rest/V1/products/<sku>/media (remember to url encode the sku) - with a body like this:



                {
                "entry": {
                "media_type": "image",
                "label": "I am an image!",
                "types": [
                "image"
                ],
                "content": {
                {
                "base64_encoded_data": <base64 encoded file>,
                "type": "image/jpeg",
                "name": "<image filename>"
                }
                },
                "file": "<image filename>"
                }
                }


                ... the image is uploaded to Magento, added to the table catalog_product_entity_media_gallery, and linked to the product. I have attached a python script for this type of request at the end of this answer.



                Unfortunately, this happens with every call of the API: the picture is uploaded again and again. Magento2 detects that a file with the same name exists already and adds an incrementor to the file name (file.jpg, file_1.jpg, file_2.jpg, ...). Such an easy way to write the harddisk full!



                This is, why in case B, things necessarily should get a bit more complex. Case B applies to situations where the script is to be executed multiple times, maybe for automation purposes. It also applies to situations where one picture is to be used for multiple skus, as in a clothes shop, where typically all sizes of the same product have different skus, but the same image.



                The entry post to https://<magento>/rest/V1/products/<sku>/media is still a great starting point, but we need to check in advance, if the file exists on the server yet.



                While it is quite easy to figure out which images are linked to a certain sku by using the API, I did not find a quick way to figure out if an image exists on the server. Therefore, an image uploading script might need to maintain a list of uploaded filenames. It could be based on the content of the table catalog_product_entity_media_gallery.



                In cases where an image exists on the server already, we only need to assign it to the product / sku. This is done via a different API call. Assuming the product has been created already, the API call would go as a PUT request to https://magento/rest/V1/products/10000%2F100%2FS:



                {
                "product": {
                "custom_attributes": {
                "image" : "<filename of the image in catalog_product_entity_media_gallery>",
                "thumbnail" : "<filename of the image in catalog_product_entity_media_gallery>",
                "small_image" : "<filename of the image in catalog_product_entity_media_gallery>"
                },
                "media_gallery_entries": [
                {
                "id": <value id of the image in catalog_product_entity_media_gallery> ,
                "media_type": "image",
                "label": "<choose an image label>",
                "position": 1,
                "disabled": true,
                "types": [
                "thumbnail"
                ],
                "file": "<filename of the image in catalog_product_entity_media_gallery>"
                }
                ]
                }
                }


                This assigns a picture, - exactly one picture to the product, and removes all other ones. We therefore need to ensure that we create one media_gallery_entry per existing image, before we send this API request.





                Here is a python3 script that uploads one image to one sku; mainly for case A:



                import requests
                import base64
                import urllib
                from json import dumps

                TOKEN='123123123123123123123123'
                IMGFILENAME='my_image_file.jpg'
                SKU='10000/100/S'
                DOMAIN='https://my-magento-domain.com'

                with open(IMGFILENAME, "rb") as image_file:
                b64_encoded_string = base64.b64encode(image_file.read()).decode("utf8")
                raw_data = {'base64_encoded_data': b64_encoded_string, 'type': 'image/jpeg', 'name': IMGFILENAME}
                json_data = dumps(raw_data, indent=2)

                url = DOMAIN + '/rest/V1/products/' + urllib.parse.quote_plus(SKU) + '/media'

                mystring = f'''
                {{
                "entry": {{
                "media_type": "image",
                "label": "my image label",
                "types": [
                "image"
                ],
                "content":
                {json_data}
                ,
                "file": "{IMGFILENAME}"
                }}
                }}
                '''

                headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
                response = requests.post(url, data=mystring, headers=headers)
                print("Response:n" + response.text + "nRequest Headers:" + response.request.headers + "nResponse Headers:" + response.headers)




                share













                For uploading and assigning images to products via API, there are two different scenarios:



                A) each image is used for exactly one SKU

                B) images can be used for multiple SKUs



                In case A, things are simple, and @mfal 's answer in this post gives enough clues to get the job done:



                Create a post to https://<magento>/rest/V1/products/<sku>/media (remember to url encode the sku) - with a body like this:



                {
                "entry": {
                "media_type": "image",
                "label": "I am an image!",
                "types": [
                "image"
                ],
                "content": {
                {
                "base64_encoded_data": <base64 encoded file>,
                "type": "image/jpeg",
                "name": "<image filename>"
                }
                },
                "file": "<image filename>"
                }
                }


                ... the image is uploaded to Magento, added to the table catalog_product_entity_media_gallery, and linked to the product. I have attached a python script for this type of request at the end of this answer.



                Unfortunately, this happens with every call of the API: the picture is uploaded again and again. Magento2 detects that a file with the same name exists already and adds an incrementor to the file name (file.jpg, file_1.jpg, file_2.jpg, ...). Such an easy way to write the harddisk full!



                This is, why in case B, things necessarily should get a bit more complex. Case B applies to situations where the script is to be executed multiple times, maybe for automation purposes. It also applies to situations where one picture is to be used for multiple skus, as in a clothes shop, where typically all sizes of the same product have different skus, but the same image.



                The entry post to https://<magento>/rest/V1/products/<sku>/media is still a great starting point, but we need to check in advance, if the file exists on the server yet.



                While it is quite easy to figure out which images are linked to a certain sku by using the API, I did not find a quick way to figure out if an image exists on the server. Therefore, an image uploading script might need to maintain a list of uploaded filenames. It could be based on the content of the table catalog_product_entity_media_gallery.



                In cases where an image exists on the server already, we only need to assign it to the product / sku. This is done via a different API call. Assuming the product has been created already, the API call would go as a PUT request to https://magento/rest/V1/products/10000%2F100%2FS:



                {
                "product": {
                "custom_attributes": {
                "image" : "<filename of the image in catalog_product_entity_media_gallery>",
                "thumbnail" : "<filename of the image in catalog_product_entity_media_gallery>",
                "small_image" : "<filename of the image in catalog_product_entity_media_gallery>"
                },
                "media_gallery_entries": [
                {
                "id": <value id of the image in catalog_product_entity_media_gallery> ,
                "media_type": "image",
                "label": "<choose an image label>",
                "position": 1,
                "disabled": true,
                "types": [
                "thumbnail"
                ],
                "file": "<filename of the image in catalog_product_entity_media_gallery>"
                }
                ]
                }
                }


                This assigns a picture, - exactly one picture to the product, and removes all other ones. We therefore need to ensure that we create one media_gallery_entry per existing image, before we send this API request.





                Here is a python3 script that uploads one image to one sku; mainly for case A:



                import requests
                import base64
                import urllib
                from json import dumps

                TOKEN='123123123123123123123123'
                IMGFILENAME='my_image_file.jpg'
                SKU='10000/100/S'
                DOMAIN='https://my-magento-domain.com'

                with open(IMGFILENAME, "rb") as image_file:
                b64_encoded_string = base64.b64encode(image_file.read()).decode("utf8")
                raw_data = {'base64_encoded_data': b64_encoded_string, 'type': 'image/jpeg', 'name': IMGFILENAME}
                json_data = dumps(raw_data, indent=2)

                url = DOMAIN + '/rest/V1/products/' + urllib.parse.quote_plus(SKU) + '/media'

                mystring = f'''
                {{
                "entry": {{
                "media_type": "image",
                "label": "my image label",
                "types": [
                "image"
                ],
                "content":
                {json_data}
                ,
                "file": "{IMGFILENAME}"
                }}
                }}
                '''

                headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN}
                response = requests.post(url, data=mystring, headers=headers)
                print("Response:n" + response.text + "nRequest Headers:" + response.request.headers + "nResponse Headers:" + response.headers)





                share











                share


                share










                answered 7 mins ago









                wherewhere

                410212




                410212






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Magento Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f137038%2fhow-to-add-product-image-when-creating-via-rest-api%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

                    How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

                    夢乃愛華...