Uploading images through the Python library

Julien_Heller
Shopify Partner
17 0 1

I'm trying to upload product images to a newly created product, and I can't get it to work. Here is my code:

import shopify
from base64 import b64encode

# Authentication variables omitted

shopify.ShopifyResource.set_site(shop_url)

path = "/path/to/file.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())
    image.attach_image(encoded, filename=filename)

new_product.images = images
new_product.save()

When I run this, the product gets added, but there are no images. Furthermore, new_product.errors.full_messages() has no items. What am I doing wrong?

0 Likes
Jakob_Külzer
Shopify Staff
Shopify Staff
15 0 4

Without knowing Python and just glancing at the source code for shopify.Image(), it looks like attach_image() will BASE64 encode the image data for you. Maybe try without encoding? 

Jakob Külzer, Shopify API Team
0 Likes
Julien_Heller
Shopify Partner
17 0 1

That was it Jakob :) This would be a lot easier if there was documentation... Every link to documentation seems to point to this page, which in turn sends me in circles. Where did the documentation go?

0 Likes
Jakob_Külzer
Shopify Staff
Shopify Staff
15 0 4

Glad I could help. 

I agree, documentation would be great; I don't work on the python library (I don't even write python ;). The bulk of the documentation is on the project's github page itself (https://github.com/Shopify/shopify_python_api). In this case, I just took a quick look at the code itself. 

Jakob Külzer, Shopify API Team
0 Likes
BeamJokerFavor
Tourist
5 0 0

I am following along here, but with a .glb format. I keep trying to upload (using API and python) and although data is transferring, it does not appear. It is also not overwriting the existing images.

glb = fetch_glb(first_product.title)
image = shopify.Image()
image.attach_image(glb, filename='{}.glb'.format(first_product.title))
first_product.images = image
first_product.save()

 

def fetch_glb(title):
...
    with open(glb_path, "rb") as image:
        f = image.read()
        return f

 

0 Likes