Quick answer: a value beginning with shpss_ is a Shopify app client secret, not an Admin API access token. Do not send it in the X-Shopify-Access-Token header. For a new merchant-owned app created in Shopify’s Dev Dashboard, exchange the client ID and shpss_ client secret for a temporary access token, then use that token to query orders and products through the GraphQL Admin API.

Table of contents

What an shpss_ value means

Shopify uses recognizable prefixes for some credentials. The prefixes help developers distinguish secrets from tokens, but they do not make the values interchangeable.

Credential Purpose How it is used
shpss_... App client secret Sent to Shopify’s token endpoint together with the client ID
shpat_... Admin API access token commonly associated with older admin-created custom apps Sent in the X-Shopify-Access-Token header
Access token returned by the token endpoint Temporary authorization for a Dev Dashboard app Sent in the X-Shopify-Access-Token header

The most common authentication mistake is this:

X-Shopify-Access-Token: shpss_...

That request normally fails because Shopify expects an access token in the header, not the app’s client secret.

For apps created through the Dev Dashboard, Shopify documents a client credentials flow in which the app sends its client ID and client secret to:

https://STORE_SUBDOMAIN.myshopify.com/admin/oauth/access_token

The response contains an access_token, granted scopes and an expires_in value. Shopify’s current Dev Dashboard flow issues tokens that expire after approximately 24 hours, so backend scripts should request a new token when necessary rather than treating it as a permanent password. See Shopify’s official Dev Dashboard token guide.

Choose the correct authentication method

The correct authentication flow depends on who owns the store and how the app was created.

Merchant-owned Dev Dashboard app

Use the client credentials grant when the app and target store belong to the same Shopify organization. Your Python backend exchanges the client ID and client secret for a temporary access token.

This is the authentication method implemented in the Python script below.

Existing admin-created custom app

An older custom app created directly inside the Shopify admin may already have an Admin API access token. That token can be supplied through the SHOPIFY_ACCESS_TOKEN environment variable.

Shopify no longer allows merchants to create new custom apps through the old Shopify-admin workflow. Existing admin-created apps can continue working, but new apps should use the Dev Dashboard or Shopify CLI.

App installed by other merchants

Do not use the client credentials grant to access unrelated merchant stores. A public or custom-distributed app installed by other merchants normally needs Shopify’s OAuth authorization flow. Each installation produces authorization associated with the merchant’s store and approved scopes.

Required Shopify API scopes

To run the exporter, configure these Admin API scopes for the app:

  • read_products for products, variants, SKUs, prices and inventory quantities;
  • read_orders for orders and line items;
  • read_all_orders only when access to orders older than Shopify’s default order window is required.

The script deliberately avoids customer names, email addresses, shipping addresses and other protected customer data. This keeps the example focused on order and product extraction while reducing privacy and approval requirements.

Shopify explains available permissions and special order access in its Admin API access scopes documentation.

After changing scopes, deploy the new app version and reinstall or update the app installation when Shopify requires it. A token only receives permissions granted to the installed app version.

Prepare the Python project

Install the HTTP library

python -m pip install requests

Configure environment variables

Store credentials in your operating system, deployment platform, CI secret store or another secure environment-variable manager. Do not paste them directly into the Python file.

Variable Required Meaning
SHOPIFY_SHOP Yes The store’s myshopify.com subdomain without .myshopify.com
SHOPIFY_CLIENT_ID For the Dev Dashboard flow The app’s client ID
SHOPIFY_CLIENT_SECRET For the Dev Dashboard flow The app client secret, often beginning with shpss_
SHOPIFY_ACCESS_TOKEN For an existing token-based installation An actual Admin API access token; do not put an shpss_ secret here
SHOPIFY_API_VERSION No Defaults to 2026-07
SHOPIFY_ORDER_QUERY No An optional Shopify order search query used to limit the export

Use either SHOPIFY_ACCESS_TOKEN or the combination of SHOPIFY_CLIENT_ID and SHOPIFY_CLIENT_SECRET. The script prioritizes an existing access token when both methods are configured.

Complete Python exporter for Shopify orders and products

The following script performs four tasks:

  1. obtains or loads an Admin API access token;
  2. queries all product variants with cursor pagination;
  3. queries available orders and paginates every order’s line items;
  4. writes flattened data to three CSV files.

The example uses the GraphQL Admin API rather than the REST Admin API. Shopify classified REST Admin as a legacy API on October 1, 2024, and new public apps have been required to use GraphQL Admin since April 1, 2025. Current fields and schema details are available in the Shopify GraphQL Admin API reference.

import csv
import os
import re
import time
from typing import Any, Dict, Iterator, Optional

import requests


SHOP = os.environ["SHOPIFY_SHOP"].strip()
API_VERSION = os.getenv("SHOPIFY_API_VERSION", "2026-07").strip()
STATIC_ACCESS_TOKEN = os.getenv("SHOPIFY_ACCESS_TOKEN", "").strip()
CLIENT_ID = os.getenv("SHOPIFY_CLIENT_ID", "").strip()
CLIENT_SECRET = os.getenv("SHOPIFY_CLIENT_SECRET", "").strip()
ORDER_QUERY = os.getenv("SHOPIFY_ORDER_QUERY", "").strip() or None

if not re.fullmatch(r"[a-z0-9][a-z0-9-]*", SHOP):
    raise ValueError(
        "SHOPIFY_SHOP must contain only the myshopify.com subdomain."
    )

BASE_URL = f"https://{SHOP}.myshopify.com"
TOKEN_URL = f"{BASE_URL}/admin/oauth/access_token"
GRAPHQL_URL = f"{BASE_URL}/admin/api/{API_VERSION}/graphql.json"

SESSION = requests.Session()
TOKEN_CACHE: Optional[str] = None
TOKEN_EXPIRES_AT = 0.0


PRODUCT_VARIANTS_QUERY = """
query ProductVariants($cursor: String) {
  productVariants(first: 100, after: $cursor) {
    nodes {
      id
      title
      sku
      barcode
      price
      inventoryQuantity
      createdAt
      updatedAt
      product {
        id
        title
        handle
        status
        vendor
        productType
        createdAt
        updatedAt
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
"""


ORDERS_QUERY = """
query Orders($cursor: String, $query: String) {
  orders(
    first: 100
    after: $cursor
    query: $query
    sortKey: CREATED_AT
  ) {
    nodes {
      id
      name
      createdAt
      processedAt
      updatedAt
      cancelledAt
      displayFinancialStatus
      displayFulfillmentStatus
      currentSubtotalPriceSet {
        shopMoney {
          amount
          currencyCode
        }
      }
      currentTotalTaxSet {
        shopMoney {
          amount
          currencyCode
        }
      }
      currentTotalPriceSet {
        shopMoney {
          amount
          currencyCode
        }
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
"""


ORDER_LINES_QUERY = """
query OrderLines($orderId: ID!, $cursor: String) {
  order(id: $orderId) {
    lineItems(first: 250, after: $cursor) {
      nodes {
        id
        title
        sku
        vendor
        variantTitle
        quantity
        currentQuantity
        originalUnitPriceSet {
          shopMoney {
            amount
            currencyCode
          }
        }
        discountedTotalSet {
          shopMoney {
            amount
            currencyCode
          }
        }
        product {
          id
        }
        variant {
          id
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
}
"""


def get_access_token() -> str:
    global TOKEN_CACHE, TOKEN_EXPIRES_AT

    if STATIC_ACCESS_TOKEN:
        return STATIC_ACCESS_TOKEN

    if not CLIENT_ID or not CLIENT_SECRET:
        raise RuntimeError(
            "Configure SHOPIFY_ACCESS_TOKEN or both "
            "SHOPIFY_CLIENT_ID and SHOPIFY_CLIENT_SECRET."
        )

    if TOKEN_CACHE and time.time() < TOKEN_EXPIRES_AT - 60:
        return TOKEN_CACHE

    response = SESSION.post(
        TOKEN_URL,
        data={
            "grant_type": "client_credentials",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
        },
        headers={
            "Content-Type": "application/x-www-form-urlencoded",
        },
        timeout=30,
    )

    if not response.ok:
        raise RuntimeError(
            f"Token request failed with HTTP {response.status_code}: "
            f"{response.text[:500]}"
        )

    payload = response.json()
    access_token = payload.get("access_token")

    if not access_token:
        raise RuntimeError("Shopify did not return an access_token.")

    expires_in = int(payload.get("expires_in", 0))
    TOKEN_CACHE = access_token
    TOKEN_EXPIRES_AT = time.time() + expires_in

    return access_token


def graphql_request(
    query: str,
    variables: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    global TOKEN_CACHE, TOKEN_EXPIRES_AT

    variables = variables or {}

    for attempt in range(6):
        response = SESSION.post(
            GRAPHQL_URL,
            json={
                "query": query,
                "variables": variables,
            },
            headers={
                "Content-Type": "application/json",
                "X-Shopify-Access-Token": get_access_token(),
            },
            timeout=60,
        )

        if response.status_code == 401 and not STATIC_ACCESS_TOKEN:
            TOKEN_CACHE = None
            TOKEN_EXPIRES_AT = 0

            if attempt < 5:
                continue

        if response.status_code in {429, 500, 502, 503, 504}:
            if attempt < 5:
                retry_after = response.headers.get("Retry-After")
                delay = (
                    float(retry_after)
                    if retry_after
                    else min(2 ** attempt, 30)
                )
                time.sleep(delay)
                continue

        if not response.ok:
            raise RuntimeError(
                f"GraphQL request failed with HTTP "
                f"{response.status_code}: {response.text[:1000]}"
            )

        payload = response.json()
        errors = payload.get("errors") or []

        if errors:
            throttled = any(
                error.get("extensions", {}).get("code") == "THROTTLED"
                for error in errors
            )

            if throttled and attempt < 5:
                time.sleep(min(2 ** attempt, 30))
                continue

            raise RuntimeError(f"GraphQL errors: {errors}")

        data = payload.get("data")

        if data is None:
            raise RuntimeError("GraphQL response did not contain data.")

        return data

    raise RuntimeError("Shopify request failed after multiple retries.")


def paginate_connection(
    query: str,
    connection_name: str,
    extra_variables: Optional[Dict[str, Any]] = None,
) -> Iterator[Dict[str, Any]]:
    cursor: Optional[str] = None
    extra_variables = extra_variables or {}

    while True:
        variables = {
            **extra_variables,
            "cursor": cursor,
        }

        data = graphql_request(query, variables)
        connection = data[connection_name]

        for node in connection["nodes"]:
            yield node

        page_info = connection["pageInfo"]

        if not page_info["hasNextPage"]:
            break

        cursor = page_info["endCursor"]


def iterate_order_lines(order_id: str) -> Iterator[Dict[str, Any]]:
    cursor: Optional[str] = None

    while True:
        data = graphql_request(
            ORDER_LINES_QUERY,
            {
                "orderId": order_id,
                "cursor": cursor,
            },
        )

        order = data.get("order")

        if order is None:
            raise RuntimeError(
                f"Shopify did not return order {order_id}."
            )

        connection = order["lineItems"]

        for line in connection["nodes"]:
            yield line

        page_info = connection["pageInfo"]

        if not page_info["hasNextPage"]:
            break

        cursor = page_info["endCursor"]


def money_value(
    money_set: Optional[Dict[str, Any]],
) -> Dict[str, str]:
    if not money_set:
        return {
            "amount": "",
            "currency": "",
        }

    shop_money = money_set.get("shopMoney") or {}

    return {
        "amount": shop_money.get("amount", ""),
        "currency": shop_money.get("currencyCode", ""),
    }


def export_products() -> int:
    fieldnames = [
        "product_id",
        "product_title",
        "product_handle",
        "product_status",
        "vendor",
        "product_type",
        "product_created_at",
        "product_updated_at",
        "variant_id",
        "variant_title",
        "sku",
        "barcode",
        "price",
        "inventory_quantity",
        "variant_created_at",
        "variant_updated_at",
    ]

    count = 0

    with open(
        "shopify_products.csv",
        "w",
        newline="",
        encoding="utf-8-sig",
    ) as csv_file:
        writer = csv.DictWriter(
            csv_file,
            fieldnames=fieldnames,
        )
        writer.writeheader()

        for variant in paginate_connection(
            PRODUCT_VARIANTS_QUERY,
            "productVariants",
        ):
            product = variant["product"]

            writer.writerow(
                {
                    "product_id": product["id"],
                    "product_title": product["title"],
                    "product_handle": product["handle"],
                    "product_status": product["status"],
                    "vendor": product.get("vendor", ""),
                    "product_type": product.get("productType", ""),
                    "product_created_at": product["createdAt"],
                    "product_updated_at": product["updatedAt"],
                    "variant_id": variant["id"],
                    "variant_title": variant["title"],
                    "sku": variant.get("sku", ""),
                    "barcode": variant.get("barcode", ""),
                    "price": variant["price"],
                    "inventory_quantity": variant.get(
                        "inventoryQuantity",
                        "",
                    ),
                    "variant_created_at": variant["createdAt"],
                    "variant_updated_at": variant["updatedAt"],
                }
            )

            count += 1

    return count


def export_orders() -> Dict[str, int]:
    order_fieldnames = [
        "order_id",
        "order_name",
        "created_at",
        "processed_at",
        "updated_at",
        "cancelled_at",
        "financial_status",
        "fulfillment_status",
        "subtotal",
        "tax",
        "total",
        "currency",
    ]

    line_fieldnames = [
        "order_id",
        "order_name",
        "order_created_at",
        "line_item_id",
        "product_id",
        "variant_id",
        "title",
        "variant_title",
        "sku",
        "vendor",
        "quantity",
        "current_quantity",
        "original_unit_price",
        "discounted_line_total",
        "currency",
    ]

    order_count = 0
    line_count = 0

    with open(
        "shopify_orders.csv",
        "w",
        newline="",
        encoding="utf-8-sig",
    ) as orders_file, open(
        "shopify_order_lines.csv",
        "w",
        newline="",
        encoding="utf-8-sig",
    ) as lines_file:
        order_writer = csv.DictWriter(
            orders_file,
            fieldnames=order_fieldnames,
        )
        line_writer = csv.DictWriter(
            lines_file,
            fieldnames=line_fieldnames,
        )

        order_writer.writeheader()
        line_writer.writeheader()

        for order in paginate_connection(
            ORDERS_QUERY,
            "orders",
            {
                "query": ORDER_QUERY,
            },
        ):
            subtotal = money_value(
                order.get("currentSubtotalPriceSet")
            )
            tax = money_value(
                order.get("currentTotalTaxSet")
            )
            total = money_value(
                order.get("currentTotalPriceSet")
            )

            order_writer.writerow(
                {
                    "order_id": order["id"],
                    "order_name": order["name"],
                    "created_at": order["createdAt"],
                    "processed_at": order.get("processedAt", ""),
                    "updated_at": order["updatedAt"],
                    "cancelled_at": order.get("cancelledAt", ""),
                    "financial_status": order.get(
                        "displayFinancialStatus",
                        "",
                    ),
                    "fulfillment_status": order.get(
                        "displayFulfillmentStatus",
                        "",
                    ),
                    "subtotal": subtotal["amount"],
                    "tax": tax["amount"],
                    "total": total["amount"],
                    "currency": total["currency"],
                }
            )

            order_count += 1

            for line in iterate_order_lines(order["id"]):
                unit_price = money_value(
                    line.get("originalUnitPriceSet")
                )
                discounted_total = money_value(
                    line.get("discountedTotalSet")
                )
                product = line.get("product") or {}
                variant = line.get("variant") or {}

                line_writer.writerow(
                    {
                        "order_id": order["id"],
                        "order_name": order["name"],
                        "order_created_at": order["createdAt"],
                        "line_item_id": line["id"],
                        "product_id": product.get("id", ""),
                        "variant_id": variant.get("id", ""),
                        "title": line["title"],
                        "variant_title": line.get(
                            "variantTitle",
                            "",
                        ),
                        "sku": line.get("sku", ""),
                        "vendor": line.get("vendor", ""),
                        "quantity": line["quantity"],
                        "current_quantity": line[
                            "currentQuantity"
                        ],
                        "original_unit_price": unit_price[
                            "amount"
                        ],
                        "discounted_line_total": discounted_total[
                            "amount"
                        ],
                        "currency": discounted_total[
                            "currency"
                        ],
                    }
                )

                line_count += 1

    return {
        "orders": order_count,
        "order_lines": line_count,
    }


def main() -> None:
    product_count = export_products()
    order_counts = export_orders()

    print(
        f"Exported {product_count} product variants, "
        f"{order_counts['orders']} orders and "
        f"{order_counts['order_lines']} order lines."
    )


if __name__ == "__main__":
    main()

Run the export

Save the script as shopify_export.py, configure the required environment variables and run:

python shopify_export.py

A successful run prints the number of exported product variants, orders and order lines.

The script validates the shop subdomain before making requests. Set SHOPIFY_SHOP to the subdomain only. Do not include https://, .myshopify.com, a slash or an admin path.

Exported CSV files

shopify_products.csv

This file contains one row per product variant. A variant-level export is usually more useful than a product-only export because SKU, barcode, price and inventory quantity belong to the variant.

Each row includes:

  • product and variant GraphQL IDs;
  • product title and handle;
  • product status, vendor and product type;
  • variant title, SKU and barcode;
  • price and aggregate inventory quantity;
  • creation and update timestamps.

shopify_orders.csv

This file contains one row per order with:

  • order ID and order number;
  • creation, processing, update and cancellation timestamps;
  • financial and fulfillment status;
  • current subtotal, tax, total and shop currency.

shopify_order_lines.csv

This file contains one row per order line. Separating order headers from order lines prevents order totals from being repeated unnecessarily and makes the files easier to import into databases, spreadsheets and analytics tools.

The line export includes SKU, product ID, variant ID, quantity, current quantity, original unit price and discounted line total.

Filter orders by date or status

Exporting every accessible order is not always necessary. Set SHOPIFY_ORDER_QUERY to a Shopify order search expression before running the script.

Useful filters include:

Objective Query
Orders created from a date created_at:>=2026-01-01
Orders created before a date created_at:<2026-07-01
Paid orders financial_status:paid
Unfulfilled orders fulfillment_status:unfulfilled
Several conditions created_at:>=2026-01-01 financial_status:paid

Date filters are especially useful for incremental synchronization. A production integration can store the latest successfully exported timestamp and request only orders created or updated after that point.

Access orders older than 60 days

The read_orders scope normally provides access to the default order window, which covers the most recent 60 days. Adding a date filter does not bypass this restriction.

To retrieve older orders, the app needs:

  • read_orders or write_orders;
  • the additional read_all_orders scope;
  • any permission or approval required by the app’s distribution and access model.

If the script returns recent orders but older orders are missing, pagination is probably not the problem. Check whether read_all_orders has been granted to the installed app.

Pagination and large stores

Shopify GraphQL connections use cursor-based pagination. The script reads pageInfo.hasNextPage and sends pageInfo.endCursor as the next request’s after value.

This is necessary because a single request does not return an unlimited number of records. Shopify allows up to 250 resources in one connection page, although using smaller pages can reduce query cost and response size.

The exporter uses a top-level productVariants connection instead of retrieving variants inside every product. This ensures products with many variants are exported across multiple pages rather than being silently truncated by a nested connection limit.

Order line items are paginated separately for every order, so an order with more than 250 lines can still be fully exported.

When to use Shopify Bulk Operations

Standard cursor pagination works well for small and medium exports. For very large stores, Shopify GraphQL Bulk Operations are usually a better option because Shopify processes the query asynchronously and provides a downloadable JSONL result.

Consider a bulk query when:

  • the store contains tens of thousands of products or orders;
  • a complete historical export takes too many API requests;
  • nested product, variant or order-line relationships are required;
  • the export runs as a scheduled data warehouse job;
  • request throttling makes synchronous pagination too slow.

Cursor pagination remains useful for incremental synchronization, recent-order polling and scripts that need results immediately.

Common errors and fixes

HTTP 401 Unauthorized

The most likely causes are:

  • an shpss_ client secret was used as the access token;
  • the access token expired;
  • the token belongs to another store;
  • the app was uninstalled;
  • the shop subdomain is incorrect.

For the Dev Dashboard flow, let the script exchange the client ID and secret for a new token. Do not manually copy the secret into SHOPIFY_ACCESS_TOKEN.

shop_not_permitted

The client credentials grant only works when the app and store belong to the same Shopify organization in the Dev Dashboard.

Check that:

  • the app appears in the intended organization;
  • the target store appears under the same organization;
  • the app is installed on that store;
  • SHOPIFY_SHOP exactly matches the store’s permanent myshopify.com subdomain.

Owning or managing a store does not automatically prove that the app and store are in the same Dev Dashboard organization.

ACCESS_DENIED or missing fields

The token is valid, but the app does not have the scope required for the requested resource.

Confirm that the installed app version includes read_products and read_orders. After changing scopes, deploy the app version and update the installation as required.

Only recent orders are returned

This usually means the app has read_orders but not read_all_orders. The API will not return older records merely because the GraphQL query asks for an earlier date.

HTTP 429 or GraphQL THROTTLED

Shopify GraphQL uses calculated query cost. The script retries HTTP 429 responses, temporary server errors and GraphQL throttle errors with exponential delays.

For a larger integration, also inspect the GraphQL response’s cost extensions, reduce unnecessary fields, cache stable data and move full catalog exports to Bulk Operations.

A GraphQL field does not exist

Shopify’s schema changes between API versions. Check the selected version and compare the query with that version’s GraphQL reference.

The example pins 2026-07. When Shopify retires that version, change SHOPIFY_API_VERSION to a supported stable version and test the query before deploying it.

Older REST tutorials no longer match the current app model

Many tutorials still use endpoints such as:

/admin/api/VERSION/orders.json
/admin/api/VERSION/products.json

Those examples may still work for some existing apps, but REST Admin is now a legacy API. New development should normally use the GraphQL Admin endpoint:

/admin/api/VERSION/graphql.json

Security rules for Shopify API credentials

  • Never commit the client secret or access token to Git.
  • Never include a real credential in a screenshot, support ticket or log entry.
  • Do not expose Admin API credentials in browser-side JavaScript.
  • Store secrets in environment variables or a managed secret vault.
  • Request only the scopes required by the integration.
  • Do not export protected customer data unless the business process genuinely requires it.
  • Restrict access to generated CSV files because order data may still be commercially sensitive.
  • Delete or rotate compromised credentials immediately.
  • Use the permanent myshopify.com domain for API calls rather than a changeable storefront domain.

A client secret beginning with shpss_ should be protected as carefully as a password. It can be used to request access tokens when the app and store qualify for the client credentials flow.

Frequently asked questions

Is shpss_ a Shopify Admin API access token?

No. It identifies an app client secret. Exchange it with the client ID through Shopify’s token endpoint. Use the returned access_token for Admin API requests.

Which header should Python send to Shopify?

GraphQL Admin API requests should include:

X-Shopify-Access-Token: ACCESS_TOKEN
Content-Type: application/json

The header must contain an actual access token, not the client secret.

Can Python extract all Shopify products?

Yes. Use the GraphQL products, productVariants or Bulk Operations APIs with pagination. The example uses productVariants so SKU, barcode, price and inventory data are exported without truncating products that contain many variants.

Can Python extract all Shopify orders?

Yes, provided the app has the necessary scopes. The standard read_orders scope normally covers the most recent 60 days. Older orders require read_all_orders in addition to an order scope.

Why does the Dev Dashboard access token expire?

Temporary tokens reduce the damage caused by an accidental leak. The app keeps the client secret secure, requests a token programmatically and refreshes it before or after expiration.

Should the temporary token be saved in a database?

It can be cached securely until shortly before expiration, but it should not be treated as a permanent credential. The script caches it only in memory and requests another token when required.

Should a new Python integration use GraphQL or REST?

Use the GraphQL Admin API for new development. REST Admin is a legacy API, while GraphQL provides the current product and order model, cursor pagination, calculated query cost and Bulk Operations.

Does inventoryQuantity show inventory by location?

No. It represents an aggregate quantity for the variant. To export inventory by location, query inventory items, inventory levels and locations with the appropriate inventory and location scopes.

Why can an order line have no product or variant ID?

An order can outlive the product or variant associated with its line item. If the catalog item was deleted, Shopify may return a line item title and SKU while the related product or variant object is null. The script handles this situation by writing an empty ID instead of failing.