AI Tools & Automation

Export Shopify Products & Inventory to Excel with Python

Shopify's built-in CSV export caps out and mangles variant data. This Python script pulls every product, variant, SKU, and inventory level via GraphQL into a clean two-sheet Excel file.

Python code exporting Shopify products, variants and inventory levels to an Excel workbook with separate sheets
On this page

Shopify’s built-in product export works fine until it doesn’t. Hit a few thousand variants, and the CSV trickles in by email, splits across files, and flattens your variant data into rows that are painful to reassemble. If you manage a catalog with multiple locations, custom metafields, or tens of thousands of SKUs, the admin export is a dead end.

The better path is the Shopify GraphQL Admin API plus a short Python script. You get exactly the fields you want — titles, SKUs, prices, barcode, inventory per location, SEO metadata — paginated properly and written straight into an Excel workbook with separate Products and Variants sheets. This guide walks through the whole thing: app creation, authentication, pagination, bulk operations for large catalogs, and the pandas export.

What You Need Before Starting

  • A Shopify store with admin access (any plan works; the API is not gated by plan tier).
  • Python 3.10+ installed locally.
  • Three packages: requests, pandas, and openpyxl (pandas needs openpyxl to write .xlsx files). Install with pip install requests pandas openpyxl.
  • Roughly 30 minutes if you’ve never touched the Shopify API.

No app review, no OAuth dance — a custom app gives you a single access token that works immediately.

What You Need Before Starting — illustration for Export Shopify Products & Inventory to Excel with Python

Step 1: Create a Shopify Custom App

Shopify deprecated standalone private apps years ago; the modern equivalent is a custom app built in the admin.

Step 1: Create a Shopify Custom App — illustration for Export Shopify Products & Inventory to Excel with Python
  1. In your Shopify admin, go to Settings → Apps and sales channels → Develop apps.
  2. Click Create an app, name it something obvious like “Inventory Exporter.”
  3. Under Configuration → Admin API integration, enable these scopes: read_products, read_inventory, and read_locations. That’s genuinely all you need for a read-only export — resist the urge to check every box.
  4. Save, then click Install app.
  5. On the API credentials tab, reveal the Admin API access token. It starts with shpat_ and is shown exactly once.

Concrete outcome: you now have a token and your store’s API endpoint, which looks like https://your-store.myshopify.com/admin/api/2025-10/graphql.json. Always pin a recent API version in the URL rather than using unstable in production scripts.

Step 2: Store the Access Token Safely

Hardcoding shpat_... into a script is how tokens end up in GitHub repos and, eventually, in breach dumps. Use an environment variable:

Step 2: Store the Access Token Safely — illustration for Export Shopify Products & Inventory to Excel with Python
python
import os
SHOP = "your-store.myshopify.com"
TOKEN = os.environ["SHOPIFY_ACCESS_TOKEN"]
API_VERSION = "2025-10"
ENDPOINT = f"https://{SHOP}/admin/api/{API_VERSION}/graphql.json"

Set it in your shell (export SHOPIFY_ACCESS_TOKEN=shpat_...) or use a .env file with python-dotenv, and add .env to .gitignore before your first commit. If the token ever leaks, uninstalling the custom app in admin revokes it instantly — one more reason custom apps beat shared credentials.

Step 3: Make Your First GraphQL Request

Shopify’s GraphQL Admin API accepts POST requests with a JSON body containing your query. A minimal fetch of products with variants and inventory:

Step 3: Make Your First GraphQL Request — illustration for Export Shopify Products & Inventory to Excel with Python
python
import requests

QUERY = """
query getProducts($cursor: String) {
  products(first: 100, after: $cursor) {
    pageInfo { hasNextPage endCursor }
    edges {
      node {
        id
        title
        handle
        status
        vendor
        productType
        seo { title description }
        variants(first: 100) {
          edges {
            node {
              id
              sku
              title
              price
              barcode
              inventoryQuantity
              inventoryItem { id }
            }
          }
        }
      }
    }
  }
}
"""

def run_query(query, variables=None):
    resp = requests.post(
        ENDPOINT,
        json={"query": query, "variables": variables or {}},
        headers={"X-Shopify-Access-Token": TOKEN,
                 "Content-Type": "application/json"},
        timeout=60,
    )
    resp.raise_for_status()
    return resp.json()

Two things to note. First, inventoryQuantity on the variant is a convenient aggregate across locations — if you need per-location stock (and multi-location merchants usually do), query inventoryLevels on the inventoryItem instead. Second, GraphQL returns exactly what you ask for, so unlike the REST API you won’t drag back megabytes of fields you never use. That matters at scale.

Step 4: Handle Variants and Pagination Correctly

This is where most DIY export scripts break. Two separate pagination layers exist:

  1. Products — paginate with pageInfo.hasNextPage and endCursor. The max page size is 250, but 100 keeps you comfortably inside Shopify’s calculated query cost limits (Shopify’s GraphQL API uses a calculated-cost rate limit with a bucket of 1000 points restoring at 50 points/second on standard plans, per Shopify’s API rate limit documentation).
  2. Variants per product — a product can theoretically exceed 100 variants only via Shopify’s expanded 2,048-variant limit rolled out to eligible stores starting in 2024. If you have products like that, paginate variants too, or use bulk operations (Step 6).

The pagination loop:

python
def fetch_all_products():
    products, cursor = [], None
    while True:
        data = run_query(QUERY, {"cursor": cursor})
        conn = data["data"]["products"]
        products.extend(edge["node"] for edge in conn["edges"])
        if not conn["pageInfo"]["hasNextPage"]:
            return products
        cursor = conn["pageInfo"]["endCursor"]

Flatten variants into their own rows while you iterate — each variant carries its parent product’s title and ID so the Excel sheets stay joinable later:

python
def flatten(products):
    product_rows, variant_rows = [], []
    for p in products:
        product_rows.append({
            "product_id": p["id"], "title": p["title"],
            "handle": p["handle"], "status": p["status"],
            "vendor": p["vendor"], "product_type": p["productType"],
            "seo_title": p["seo"]["title"],
            "seo_description": p["seo"]["description"],
        })
        for edge in p["variants"]["edges"]:
            v = edge["node"]
            variant_rows.append({
                "product_id": p["id"], "product_title": p["title"],
                "variant_id": v["id"], "variant_title": v["title"],
                "sku": v["sku"], "barcode": v["barcode"],
                "price": v["price"],
                "inventory_quantity": v["inventoryQuantity"],
                "inventory_item_id": v["inventoryItem"]["id"],
            })
    return product_rows, variant_rows

Outcome: two clean, normalized lists — one row per product, one row per variant — which is exactly how a merchandiser or analyst wants the data.

Step 5: Write the Excel Workbook with pandas

With the flattened data, the export itself is three lines:

python
import pandas as pd

product_rows, variant_rows = flatten(fetch_all_products())

with pd.ExcelWriter("shopify_export.xlsx", engine="openpyxl") as writer:
    pd.DataFrame(product_rows).to_excel(writer, sheet_name="Products", index=False)
    pd.DataFrame(variant_rows).to_excel(writer, sheet_name="Variants", index=False)

Why Excel and not CSV? Because a single .xlsx with separate Products and Variants worksheets preserves the one-to-many relationship without forcing anyone to reconcile multiple CSV files. If you want polish, add openpyxl touches — freeze the header row, auto-size columns, format the price column as currency. For a weekly ops report, that formatting pays for itself immediately.

Schedule it with cron or a GitHub Action, and you have an automated inventory snapshot your warehouse team can open without touching the Shopify admin.

Step 6: Use Bulk Operations for Large Catalogs

Cursor pagination works well up to roughly 10,000–20,000 products. Beyond that, sequential requests get slow and you’ll occasionally brush against cost limits. Shopify Bulk Operations solve this: you submit one query, Shopify prepares the full result set asynchronously, and you download a JSONL file.

python
BULK_QUERY = """
mutation {
  bulkOperationRunQuery(query: \"\"\"
    { products { edges { node { id title variants { edges { node { sku price inventoryQuantity } } } } } } }
  \"\"\") {
    bulkOperation { id status }
    userErrors { field message }
  }
}
"""

Then poll currentBulkOperation until status is COMPLETED, download the url it returns, and parse the JSONL line by line into the same flatten() function. A catalog of 100,000 variants that would take dozens of paginated requests completes as one server-side operation. Note the one-at-a-time restriction: Shopify allows a single running bulk operation per shop, so queue rather than parallelize.

Pro Tips and Common Mistakes

Pitfall Symptom Fix
Missing scopes ACCESS_DENIED on variants or inventory Re-check read_products / read_inventory in app config, reinstall app
Wrong API version 404 or deprecation warnings Pin a supported version like 2025-10 in the endpoint URL
Throttling THROTTLED errors in GraphQL response Read extensions.cost.throttleStatus, back off until currentlyAvailable recovers
Token in code Leaked credentials Environment variables + .gitignore; revoke by uninstalling the app
Ignoring userErrors Silent failures on mutations Always check userErrors on bulk operation submissions
Assuming one location Inventory totals look wrong Query inventoryLevels per location via inventoryItem

Two more from experience: always request extensions.cost during development so you can see how expensive your query actually is, and never use time.sleep() as your only throttle strategy — the throttleStatus field tells you exactly when you’re safe to continue.

FAQ

Can I export Shopify products to Excel without an app?

Yes — admin → Products → Export gives you a CSV, which Excel opens directly. But it caps at your filtered view, arrives by email for large catalogs, and flattens variants awkwardly. For anything automated or beyond a few thousand SKUs, the API route in this guide is more reliable.

What is the difference between Shopify’s REST and GraphQL Admin APIs for exports?

GraphQL lets you request exactly the fields you need and traverse products → variants → inventory in one query, while REST forces multiple endpoints and returns fixed payloads. Shopify has designated GraphQL as the primary Admin API going forward, so new export tooling should target GraphQL.

How do I handle Shopify API rate limits in Python?

GraphQL uses a calculated-cost bucket: on standard plans you get 1,000 points restoring at 50 per second, per Shopify’s rate limit documentation. Check extensions.cost.throttleStatus.currentlyAvailable in every response and pause when it drops near your query’s cost. For big jobs, bulk operations sidestep throttling almost entirely.

Can I export inventory per location with the Shopify API?

Yes. Query inventoryItem { inventoryLevels(first: 10) { edges { node { location { name } quantities(names: [\"available\"]) { quantity } } } } } on each variant. The variant-level inventoryQuantity field only returns an aggregate, which hides location splits.

Is there a limit to how many products the Shopify API can export?

No hard cap — but pagination practicality is. Cursor pagination is fine into the low tens of thousands of products; for larger catalogs, bulk operations process the entire dataset server-side and return one JSONL file, with only one bulk operation allowed to run per shop at a time.

Wrapping Up

You now have a repeatable pipeline: custom app token → paginated GraphQL query → flattened product and variant rows → a two-sheet Excel workbook, with bulk operations in your back pocket for when the catalog outgrows cursor pagination. Total runtime for a 5,000-variant store is usually under a minute.

Take the script further: add metafields to the query for enriched reporting, schedule it nightly, or pipe the same DataFrames into Google Sheets for a live ops dashboard. If you’re building more Shopify automations, check our guides on inventory sync and order data pipelines — the token and query scaffolding you built here carries straight over.