python - Trying to make an API call on Bricklink - Stack Overflow

admin2025-04-17  3

I should start of saying I am in no way a programmer, I am basically someone in finance that has some sort of idea of data analysis. I've asked ChatGPT (the free version) to write me a code that could access the Bricklink API (which is a site for buying and selling LEGO). It would then, of one set, download the inventory data and amend it with price guide data. That price guide data would be fetched for each part in the inventory of the set and contains information about the number of items and lots sold, number of items and lots currently for sale and the price for which the items is sold in the last 6 months.

Somehow the inventory is downloaded but then the rest of the info is not added. The warning I get is as follows:

Warning: Missing or malformed 'item' key in inventory data: {'match_no': 0, 'entries': [{'item': {'no': '2431', 'name': 'Tile 1 x 4', 'type': 'PART', 'category_id': 37}, 'color_id': 85, 'quantity': 8, 'extra_quantity': 0, 'is_alternate': False, 'is_counterpart': False}]}

So I am hoping that there is a simple solution for my problem that I cannot fix and ChatGPT also has a lot of trouble with...

The code used is as follows

    import requests
    from requests_oauthlib import OAuth1
    import pandas as pd

    # BrickLink API credentials (Replace these with your actual credentials)
    CONSUMER_KEY = 'redacted'
    CONSUMER_SECRET = 'redacted'
    TOKEN_VALUE = 'redacted'
    TOKEN_SECRET = 'redacted'

    # Base URL for BrickLink API
    BASE_URL = ";

    def get_set_inventory(set_num):
    """Fetches inventory (part list) of a LEGO set."""
    set_num_with_version = f"{set_num}-1" if "-" not in set_num else set_num  # Ensure     -1 is added if missing
    url = f"{BASE_URL}/items/SET/{set_num_with_version}/subsets"
    auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_VALUE, TOKEN_SECRET)
    response = requests.get(url, auth=auth)
    if response.status_code == 200:
        return response.json().get("data", [])
    else:
        print(f"Error fetching inventory: {response.status_code}")
        return []

    def extract_parts(inventory_data):
    """Extracts parts (part number, name, and quantity) from the inventory data."""
    parts_list = []
    
    # Loop through items in the inventory
    for item in inventory_data:
        # Loop through entries within each item
        entries = item.get('entries', [])
        if not entries:
            print(f"Warning: No entries found for item {item}")
            continue  # Skip if no entries
        
        # Process each entry
        for entry in entries:
            item_data = entry.get('item', None)
            if item_data is None:
                print(f"Warning: Missing 'item' key in entry {entry}")
                continue  # Skip if 'item' data is missing
            
            # Extract part details
            part_no = item_data.get('no')
            part_name = item_data.get('name')
            quantity = entry.get('quantity', 0)  # Default to 0 if no quantity
            
            # Add the part to the list
            parts_list.append({
                'Part Number': part_no,
                'Part Name': part_name,
                'Quantity': quantity
            })
    
    return parts_list

    def save_parts_to_excel(parts_list, filename="lego_parts.xlsx"):
    """Saves the parts list to an Excel file."""
    if parts_list:
        df = pd.DataFrame(parts_list)
        df.to_excel(filename, index=False)
        print(f"Parts list has been saved to {filename}")
    else:
        print("No parts data to save.")

    def main():
    set_num = input("Enter LEGO set number: ")
    inventory = get_set_inventory(set_num)
    
    # Check if inventory is populated
    if not inventory:
        print("Inventory is empty!")
    else:
        print(f"Inventory contains {len(inventory)} items.")
        
        # Extract parts from the inventory data
        parts_list = extract_parts(inventory)
        
        # Save the parts to an Excel file
        save_parts_to_excel(parts_list)

    if __name__ == "__main__":
    main()

I've tried running it through ChatGPT a few times and tried to understand the code myself. Both failed (miserably). Hoping that someone recognizes the warning and can tell me which part of this program isn't working.

转载请注明原文地址:http://anycun.com/QandA/1744887817a89037.html