Magento – How to add media gallery entries via REST API – Magento 2

gallerymagento2.0.8mediarest

I stored image in pub/media/catalog/product. How to add that images into media gallery entries.

I have tried like http://myhost/rest/V1/products

"media_gallery_entries"=> array(
    array(
        "media_type"=> "image",
        "label"=> "Product Image",
        "position"=> 1,
        "disabled"=> false,
        "types"=> array(
            "image",
            "small_image",
            "thumbnail"
        ),
        "file"=> "/1/0/10.jpg"
    )
),

but it always complain about "message":"The image content is not valid."

base64_encode is the only way to add image into rest api?

if yes I tried with

"media_gallery_entries"=> array(
    array(
        "media_type"=> "image",
        "label"=> "Product Image",
        "position"=> 1,
        "disabled"=> false,
        "types"=> array(
            "image",
            "small_image",
            "thumbnail"
        ),
        "content"=> array(
            "base64_encoded_data"=> $data->getMainImage(),
            "type"=> "image/jpeg",
            "name"=> "test.jpg"
        ),
    )
),

It throws exception "message":"The image MIME type is not valid or not supported."

I found supported mime type in /vendor/magento/framework/Api/ImageContentValidator.php

private $defaultMimeTypes = [
    'image/jpg',
    'image/jpeg',
    'image/gif',
    'image/png',
];

It support image/jpeg, but I don't know why it throws exception.

Can anyone enlighten me to how to add media galleries entries?

Best Answer

Try with your second example, but instead of media_type, use mediaType tag.

"media_gallery_entries"=> array(
    array(
        "media_type"=> "image",
        "label"=> "Product Image",
        "position"=> 1,
        "disabled"=> false,
        "types"=> array(
            "image",
            "small_image",
            "thumbnail"
        ),
        "content"=> array(
            "base64_encoded_data"=> $data->getMainImage(),
            "type"=> "image/jpeg",
            "name"=> "test.jpg"
        ),
    )
),

Also, you'll probably have to use base64_encode($data->getMainImage()) instead of $data->getMainImage() only.

Related Topic