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?

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

Why is it a bad idea to hire a hitman to eliminate most corrupt politicians?

What exploit are these user agents trying to use?

Infinite Abelian subgroup of infinite non Abelian group example

I would say: "You are another teacher", but she is a woman and I am a man

Has there ever been an airliner design involving reducing generator load by installing solar panels?

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

Why do I get two different answers for this counting problem?

How can I tell someone that I want to be his or her friend?

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

How can saying a song's name be a copyright violation?

Twin primes whose sum is a cube

Today is the Center

Where does SFDX store details about scratch orgs?

Stopping power of mountain vs road bike

Alternative to sending password over mail?

Is it inappropriate for a student to attend their mentor's dissertation defense?

Emailing HOD to enhance faculty application

SSH "lag" in LAN on some machines, mixed distros

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

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

Is "remove commented out code" correct English?

Why are electrically insulating heatsinks so rare? Is it just cost?

Facing a paradox: Earnshaw's theorem in one dimension



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 8 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

                    Disable / Remove link to Product Items in Cart Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?How can I limit products that can be bought / added to cart?Remove item from cartHide “Add to Cart” button if specific products are already in cart“Prettifying” the custom options in cart pageCreate link in cart sidebar to view all added items After limit reachedLink products together in checkout/cartHow to Get product from cart and add it againHide action-edit on cart page if simple productRemoving Cart items - ObserverRemove wishlist items when added to cart

                    Helsingin valtaus Sisällysluettelo Taustaa | Yleistä sotatoimista | Osapuolet | Taistelut Helsingin ympäristössä | Punaisten antautumissuunnitelma | Taistelujen kulku Helsingissä | Valtauksen jälkeen | Tappiot | Muistaminen | Kirjallisuutta | Lähteet | Aiheesta muualla | NavigointivalikkoTeoksen verkkoversioTeoksen verkkoversioGoogle BooksSisällissota Helsingissä päättyi tasan 95 vuotta sittenSaksalaisten ylivoima jyräsi punaisen HelsinginSuomalaiset kuvaavat sotien jälkiä kaupungeissa – katso kuvat ja tarinat tutuilta kulmiltaHelsingin valtaus 90 vuotta sittenSaksalaiset valtasivat HelsinginHyökkäys HelsinkiinHelsingin valtaus 12.–13.4. 1918Saksalaiset käyttivät ihmiskilpiä Helsingin valtauksessa 1918Teoksen verkkoversioTeoksen verkkoversioSaksalaiset hyökkäävät Etelä-SuomeenTaistelut LeppävaarassaSotilaat ja taistelutLeppävaara 1918 huhtikuussa. KapinatarinaHelsingin taistelut 1918Saksalaisten voitonparaati HelsingissäHelsingin valtausta juhlittiinSaksalaisten Helsinki vuonna 1918Helsingin taistelussa kaatuneet valkokaartilaisetHelsinkiin haudatut taisteluissa kaatuneet punaiset12.4.1918 Helsingin valtauksessa saksalaiset apujoukot vapauttavat kaupunginVapaussodan muistomerkkejä Helsingissä ja pääkaupunkiseudullaCrescendo / Vuoden 1918 Kansalaissodan uhrien muistomerkkim

                    Adjektiivitarina Tarinan tekeminen | Esimerkki: ennen | Esimerkki: jälkeen | Navigointivalikko