WooCommerce Python REST API Client

3.0.0 · active · verified Thu Apr 16

The `woocommerce` library is an official Python wrapper for the WooCommerce REST API, enabling developers to easily interact with WooCommerce stores. It is currently at version 3.0.0, released in March 2021, and its development cadence is generally infrequent, tied to significant updates or changes in the core WooCommerce REST API.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `woocommerce.API` client and fetch products from your store. Remember to replace the placeholder URL and API keys with your actual store details, preferably by loading them from environment variables for security.

import os
from woocommerce import API

# --- Instructions to get API keys --- #
# 1. Log into your WordPress admin for the WooCommerce store.
# 2. Go to WooCommerce > Settings > Advanced > REST API.
#    (Prior to WooCommerce 3.4, this was WooCommerce > Settings > API > Keys/Apps).
# 3. Click 'Add key'.
# 4. Enter a description, choose a user, set permissions (e.g., 'Read/Write'), and click 'Generate API key'.
# 5. Copy the generated Consumer Key (starts with 'ck_') and Consumer Secret (starts with 'cs_').
# 6. Set these as environment variables or replace the placeholders below.

# Replace with your store URL, consumer key, and consumer secret
STORE_URL = os.environ.get('WOOCOMMERCE_STORE_URL', 'https://your-store.com')
CONSUMER_KEY = os.environ.get('WOOCOMMERCE_CONSUMER_KEY', 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
CONSUMER_SECRET = os.environ.get('WOOCOMMERCE_CONSUMER_SECRET', 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

wcapi = API(
    url=STORE_URL,
    consumer_key=CONSUMER_KEY,
    consumer_secret=CONSUMER_SECRET,
    version='wc/v3', # Default and recommended API version
    verify_ssl=True # Set to False for self-signed certificates (not recommended for production)
)

try:
    # Example: Retrieve a list of products
    print(f"Attempting to fetch products from {STORE_URL}...")
    products = wcapi.get("products").json()
    if products:
        print(f"Successfully fetched {len(products)} products.")
        print("First product title:", products[0].get('name'))
    else:
        print("No products found or empty response.")

    # Example: Retrieve a specific product (replace 123 with an actual product ID)
    # product_id = 123 # Replace with a valid product ID
    # single_product = wcapi.get(f"products/{product_id}").json()
    # if single_product:
    #     print(f"\nFetched product ID {product_id}: {single_product.get('name')}")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please check your URL, API keys, permissions, and network connectivity.")

view raw JSON →