Ad

Shopify API Upload A Local Image Via Python

- 1 answer

import shopify
from base64 import b64encode
#omitted the shopify key
shopify.ShopifyResource.set_site(shop_url)


path = "product.jpg"

new_product = shopify.Product()
new_product.title = "title"
new_product.body_html = "This is a test"

image = shopify.Image()

with open(path, "rb") as f:
    filename = path.split("/")[-1:][0]
    #encoded = b64encode(f.read()) (I tried this one as well)
    encoded = f.read()
    image.attach_image(encoded, filename=filename)

new_product.images = image
new_product.save()

I tested both methods:

  • encoded = b64encode(f.read())
  • encoded = f.read()

In both tests, the output was the same:

The product was successfully created, however, with no image.

I also noticed that the image returns image(None) and new_products.images returns image(None) as well.

Ad

Answer

You were so close- the new_product.images attribute must be a list of Image instances, not an Image instance. Also, if you look at the source of attach_image(), you can see they do the base64 encoding for you.

import shopify
#omitted the shopify key
shopify.ShopifyResource.set_site(shop_url)

path = "product.jpg"

new_product = shopify.Product()
new_product.title = "title"
new_product.body_html = "This is a test"

image = shopify.Image()

with open(path, "rb") as f:
    filename = path.split("/")[-1:][0]
    encoded = f.read()
    image.attach_image(encoded, filename=filename)

new_product.images = [image] # Here's the change
new_product.save()
Ad
source: stackoverflow.com
Ad