I’m working with Shopify’s Python API and running into an issue when trying to attach multiple images to one product. My code seems to only upload the first image, even though I’m creating two separate image objects and adding them to the product’s images array.
It’s not just about reading the wrong files. Shopify processes multiple images asynchronously during product creation and can fail silently due to conflicts or rate limiting. I’ve had way better luck creating the product first, then adding images separately.
After your product.save() call, add images one by one:
product.save()
for image_file in [first_image, second_image]:
img = shopify.Image({'product_id': product.id})
with open(image_file, "rb") as f:
img.attach_image(f.read(), filename=image_file.split("/")[-1])
img.save()
This gives you better error handling and dodges the bulk upload problems you get with the images array method. Plus you’ll actually know if an image upload fails.
You’re reading the image data only once from the first file and using it for both images. You open first_image but never read from second_image, so both image objects end up with the same data from car1.png. Shopify probably filters this out as a duplicate.
Read each file separately instead:
first_img = shopify.Image()
second_img = shopify.Image()
with open(first_image, "rb") as img_file:
img_data1 = img_file.read()
first_img.attach_image(img_data1, filename=first_image.split("/")[-1])
with open(second_image, "rb") as img_file:
img_data2 = img_file.read()
second_img.attach_image(img_data2, filename=second_image.split("/")[-1])
I ran into this exact same problem before and wasted way too much time debugging it. The attach_image method works fine - you just need to make sure each Image object gets its own unique data.
Try a different approach - skip attach_image and set the image src directly with base64 encoding. I’ve had better luck with this method for multiple images.
import base64
first_img = shopify.Image()
second_img = shopify.Image()
with open(first_image, "rb") as f:
first_img.src = "data:image/png;base64," + base64.b64encode(f.read()).decode()
with open(second_image, "rb") as f:
second_img.src = "data:image/png;base64," + base64.b64encode(f.read()).decode()
product.images = [first_img, second_img]
Or upload images after you create the product instead of during creation. Create the product first, then add images to the existing product ID. Shopify’s API handles this way more consistently - works better in production.
ur opening first_image twice but never reading second_image. both images have same car1.png data, so shopify sees it as a duplicate. open each file separately like owen said, or upload images one at a time after creating the product - way easier that way.