Need Assistance With Shopify Python API - Creating Variants

Highlighted
New Member
1 0 0

Hello,

I have found a lot of assistance from the users on this forum and hoping someone can help me figure out why my script isn't working properly. I have created a python script using the Shopify API which does the following:

  1. Pull vendor inventories into a centralized database
  2. Check if a vendor product and/or variant exists in Shopify:
    1. If product doesn't exist, create it. Check again if it exists.
  3. Grab the product_id from Shopify API
  4. For each variant that does not currently exist in Shopify:
    1. Create variant
    2. Create image URL links for variant

 

Now, the script I am using is successful in creating products and linking the image URLs but it is not successful when creating the variants. Because of this, all products that do get created successfully do not have the pricing/option/measurement data which is necessary for the Shopify store to have. I've listed my code below with hope that someone will see the error in my ways and provide clarity!

 

print("Creating new Shopify products/variants...")
session = shopify.Session(shop_url, api_version, token)
shopify.ShopifyResource.activate_session(session)

shop = shopify.Shop.current() # Get the current shop

for product in ProductCreations:
Title = product['Title']
BodyHTML = product['Body (HTML)']
Vendor = product['Vendor']
Type = product['Type']
Handle = product['Handle']
Published = "false" # product['Published']
SEOTitle = product['SEO Title']
SEODescription = product['SEO Description']
Tags = product['Tags']
Imagesrc=product['Image Src']
ImageAltText = product['Image Alt Text']
Status = "draft" # Change to 'active' if requested by client
print(Title)


DoesProductAlreadyExist = shopify.Product.find(title=Title)
print(f"DoesItExist? {DoesProductAlreadyExist}")

while len(DoesProductAlreadyExist) == 0:
print("Creating product...")
# Create a new product
new_product = shopify.Product()
new_product.title = Title
new_product.body_html = BodyHTML
new_product.vendor = Vendor
new_product.product_type = Type
new_product.handle = Handle
new_product.published = Published
new_product.metafields_global_title_tag = SEOTitle
new_product.metafields_global_description_tag = SEODescription
new_product.tags = Tags
new_product.status = Status

success = new_product.save() # returns false if the record is invalid
print(success)

# Assign image to product
product_id = new_product.id

image = shopify.Image()
image.product_id = product_id
image.src=ImageSrc
image.alt = ImageAltText
imageSuccess = image.save()
print(imageSuccess)

DoesProductAlreadyExist = shopify.Product.find(title=Title)
print(f"DoesItExist? {DoesProductAlreadyExist}")

product_id = DoesProductAlreadyExist[0]
for variant in VariantCreations:
VariantHandle = variant['Handle']
VariantPrice = variant['Variant Price']
VariantCompareAtPrice = variant['Variant Compare At Price']
VariantCost = variant['Variant Cost']
VariantBarcode = variant['Variant Barcode']
VariantSKU = variant['Variant SKU']
VariantRequiresShipping = variant['Variant Requires Shipping']
VariantInventoryPolicy = variant['Variant Inventory Policy']
VariantInventoryTracker = variant['Variant Inventory Tracker']
VariantTaxable = variant['Variant Taxable']
VariantGrams = variant['Variant Grams']
VariantWeight = variant['Variant Weight']
VariantWeightUnit = variant['Variant Weight Unit']
VariantFulfillmentService = variant['Variant Fulfillment Service']
VariantImage = variant['Variant Image']
String = variant['Option1 Value']

if VariantHandle == Handle:
print(VariantHandle)

if "{" in String:
print("Replacing {}")
StringReplace = String.replace("}", "").replace("{", "")
StringToList = StringReplace.split(",")
FinalOptionsList = []
for item in StringToList:
if "value" in item:
item = item.replace("value: ", "")
FinalOptionsList.append(item)
FinalOptionsString = " ".join(FinalOptionsList).replace(" ", " ")
if "|" in String:
print("Replacing |")
FinalOptionsString = String.replace("|", " ")
if "|" not in String and "{" not in String and "," in String:
print("Replacing ,")
FinalOptionsString = String.replace(",", " ").replace(" ", " ")

print(f"FinalOptionsString: {FinalOptionsString}")
product_id.options = [
{"name": "Description"}
]

product_id.variants = []
variant = shopify.Variant()
variant.option1 = FinalOptionsString
variant.price = VariantPrice
variant.compare_at_price = VariantCompareAtPrice
variant.cost = VariantCost
variant.barcode = VariantBarcode
variant.sku = VariantSKU
variant.requires_shipping = VariantRequiresShipping
variant.inventory_policy = VariantInventoryPolicy
variant.inventory_management = VariantInventoryTracker
variant.taxable = VariantTaxable
variant.grams = VariantGrams
variant.weight = VariantWeight
variant.weight_unit = VariantWeightUnit
variant.fulfillment_service = VariantFulfillmentService

product_id.variants.append(variant)

success = product_id.save() # returns false if the record is invalid
print(f"Saved Variant: {success}")

print("Adding image(s) to variants...")
# Need to split up variant images and send each to Shopify for current variant
SplitString = VariantImage.rsplit('/', 1)
BaseImageURL = SplitString[0]
VariantImages = list(SplitString[1].split("|"))
for image in VariantImages:
ImageURL = f"{BaseImageURL}/{image}"
# product_id = variant.id

image = shopify.Image({"product_id": product_id.id})
# image.product_id = str(product_id).replace("product(", "").replace(")", "")
# print(f"Image ProductID: {image.product_id}")
image.src=ImageURL
image.alt = ImageAltText
imageSuccess = image.save()
print(f"Saved Image: {imageSuccess}")
0 Likes