New Shopify Certification now available: Liquid Storefronts for Theme Developers

For a specific Tag my script finds 239 product instead of existing 4 products using Admin API

8 0 1

I've created a script, that uses the Admin API to get the product list by a specific tag that is defined and then gets the title and description of each product in the list to use the OpenAI-API to update the product titles and descriptions.


When I search for the tagged products on Shopify I can find 4 products.


But my script is finding 239 products which is not possible. I was not able to find the issue. 


Can someone help localize the issue??


Here is my script:

import logging
import openai
import shopify
import json
import requests

# Configure logging
logging.basicConfig(filename='script.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Function to read tag from file
def read_tag(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        tag = file.readline().strip()
    return tag

# Function to read prompts from file
def read_prompts(filename):
    prompts = {}
    with open(filename, 'r', encoding='utf-8') as file:
        current_key = ''
        for line in file:
            if ': ' in line:
                key, prompt = line.strip().split(': ', 1)
                current_key = key
                prompts[key] = prompt
                # Assuming continuation of the current prompt
                prompts[current_key] += ' ' + line.strip()
    return prompts

# Set up OpenAI API
openai_api_key = 'XYZ'
openai.api_key = openai_api_key

# Set up Shopify API
API_VERSION = '2023-04'
SHOP_NAME = 'b5714b-2'

shop_url = f"https://{SHOP_NAME}{API_VERSION}"

headers = {
    'Content-Type': 'application/json',
    'X-Shopify-Access-Token': ACCESS_TOKEN

def get_products_by_tag(tag):
    tagged_products = []
    url = f'{shop_url}/products.json?limit=50&tags={tag}'
    while url:
        response = requests.get(url, headers=headers)
        if response.status_code != 200:
            logging.error(f'Failed to retrieve products: {response.text}')
        data = response.json()
        link_header = response.headers.get('Link', '')
        url = None  # Reset URL
        for link in link_header.split(','):
            if 'rel="next"' in link:
                # Updated this line to remove < and > using replace method
                url = link.split(';')[0].replace('<', '').replace('>', '')
                break  # Exit loop once the next page URL is found
    return tagged_products

def main():
    # Read the tag from file
    tag_to_search = read_tag('tag.txt')
    # Search for products with the specified tag
    tagged_products = get_products_by_tag(tag_to_search)'Found {len(tagged_products)} products with tag: {tag_to_search}')

    # Load prompts from file
    prompts = read_prompts('prompts.txt')

    for product in tagged_products:
            # Generate product title and description using OpenAI
            response_title = openai.ChatCompletion.create(
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": f"{prompts['title_prompt']} Previous title: {product['title']}"}

            # Adjust the prompt to request HTML formatted response
            html_prompt = f"{prompts['description_prompt']} Please provide the description in HTML format with headings, paragraphs, and lists as appropriate but don't change the text or heading color. Previous description: {product['body_html']}"

            response_description = openai.ChatCompletion.create(
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": html_prompt}

            # Update product title and description on Shopify
            product_update = {
                'product': {
                    'id': product['id'],
                    'title': response_title['choices'][0]['message']['content'].strip(),
                    'body_html': response_description['choices'][0]['message']['content'].strip()
            update_url = f"{shop_url}/products/{product['id']}.json"
            update_response = requests.put(update_url, headers=headers, json=product_update)
            if update_response.status_code != 200:
                logging.error(f'Failed to update product {product["id"]}: {update_response.text}')
      'Successfully processed product {product["id"]}')
        except Exception as e:
            logging.exception(f'Error processing product {product["id"]}')

if __name__ == "__main__":

Here is the log:
2023-10-21 16:37:58, 172 - INFO - Found 239 products with tag: PQWERYWERY


here is what Shopify finds:
Bildschirmfoto 2023-10-21 um 16.43.59.png

Replies 0 (0)