WooCommerce Python REST API Client
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
-
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
cause The API returned HTML content (e.g., a login page or an error page) instead of valid JSON. This often indicates an incorrect API endpoint URL, a redirect, or authentication failure where the server responds with an HTML error page.fixVerify that your `url` points to the correct WooCommerce store base URL (e.g., `https://your-store.com`), and that your consumer key and secret are correct and have the necessary permissions. Also, ensure your endpoint is a valid REST API path (e.g., 'products' not a regular product page URL). Check `response.text` for the actual HTML content to debug. If using HTTP, try `query_string_auth=True`. -
woocommerce.exceptions.WooCommerceHTTPError: Error: 401 Unauthorized (Consumer key is missing)
cause The API request failed due to missing or invalid authentication credentials. This could be incorrect consumer key/secret, insufficient permissions for the keys, or the `Authorization` header being stripped by your server (especially with HTTP).fixDouble-check your `consumer_key` and `consumer_secret`. Ensure the keys generated in WooCommerce admin have 'Read' or 'Read/Write' permissions as required. If using HTTP, try `query_string_auth=True`. Make sure the user associated with the API key still exists. -
{'code': 'empty_data', 'message': 'Not enough data to create this user.', 'data': {'status': 400}}cause This error occurs when attempting to create or update a resource (e.g., customer, product) via a POST/PUT request, but the provided `data` dictionary is missing one or more required fields or is empty.fixConsult the WooCommerce REST API documentation for the specific endpoint you are using (e.g., `/customers`, `/products`) to identify all required fields for creation/update and ensure they are present in your `data` payload. For customers, a password is often a critical missing field. -
ModuleNotFoundError: No module named 'woocommerce'
cause The `woocommerce` library has not been installed in your Python environment or the environment where your script is running is not the one where the library was installed.fixRun `pip install woocommerce` in your terminal. If using a virtual environment, ensure it's activated before installation and script execution.
Warnings
- breaking Version 3.0.0 dropped support for legacy Python versions. It now requires Python 3.6 or newer. If upgrading from a pre-3.0.0 library version, ensure your Python environment meets this requirement.
- gotcha When using Basic Authentication over plain HTTP (not HTTPS), the `Authorization` header may be stripped by some servers. To work around this, set `query_string_auth=True` in the `API` constructor to force authentication credentials into the query string. This is not recommended for production environments due to security implications.
- deprecated The `wp_api` parameter in the `API` constructor, previously used to enable requests to the WP REST API, is now considered deprecated or its usage inverted. For modern WooCommerce APIs (version 'wc/v3'), you typically don't need to specify `wp_api=True`. Setting `wp_api=False` might be needed for genuinely legacy WooCommerce API versions.
- gotcha When testing with self-signed SSL certificates or local development setups, `verify_ssl=True` will cause SSL certificate validation errors. Set `verify_ssl=False` in the `API` constructor to bypass this validation, but be aware this compromises security and should not be used in production.
Install
-
pip install woocommerce
Imports
- API
from woocommerce import API
Quickstart
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.")