WooCommerce REST API
Overview
WooCommerce ships a versioned REST API (/wp-json/wc/v3/) that exposes products, orders, customers, coupons, and store settings over HTTPS. It uses OAuth 1.0a for non-HTTPS environments and Basic Auth (consumer key/secret) over HTTPS. The official @woocommerce/woocommerce-rest-api Node.js client handles authentication automatically and supports the full CRUD surface.
When to Use This Skill
- When building a headless storefront that reads products and categories from WooCommerce
- When integrating WooCommerce with an ERP, CRM, or fulfillment system
- When creating an order management dashboard outside of WordPress Admin
- When syncing inventory between WooCommerce and a warehouse or POS system
- When automating bulk product imports or price updates from an external catalog
- When building a mobile app that needs access to WooCommerce store data
Core Instructions
Generate API credentials
In WordPress Admin → WooCommerce → Settings → Advanced → REST API → Add Key:
- Description:
My Integration
- User: (admin user)
- Permissions: Read/Write
This generates a Consumer Key (ck_xxx) and Consumer Secret (cs_xxx). Store them in environment variables, never in source code.
WOOCOMMERCE_URL=https://mystore.com
WOOCOMMERCE_CONSUMER_KEY=ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
WOOCOMMERCE_CONSUMER_SECRET=cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Set up the Node.js client
npm install @woocommerce/woocommerce-rest-api
// lib/woocommerce.ts
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";
export const woo = new WooCommerceRestApi({
url: process.env.WOOCOMMERCE_URL!,
consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY!,
consumerSecret: process.env.WOOCOMMERCE_CONSUMER_SECRET!,
version: "wc/v3",
axiosConfig: {
timeout: 15000,
},
});
Query products with filtering and pagination
// lib/products.ts
interface ProductQuery {
page?: number;
perPage?: number;
category?: number;
status?: "publish" | "draft" | "private";
stockStatus?: "instock" | "outofstock" | "onbackorder";
orderby?: "date" | "popularity" | "price" | "title";
}
export async function getProducts(params: ProductQuery = {}) {
const response = await woo.get("products", {
page: params.page ?? 1,
per_page: params.perPage ?? 20,
status: params.status ?? "publish",
stock_status: params.stockStatus,
orderby: params.orderby ?? "date",
category: params.category,
});
return {
products: response.data,
totalPages: parseInt(response.headers["x-wp-totalpages"]),
totalProducts: parseInt(response.headers["x-wp-total"]),
};
}
export async function getProductById(id: number) {
const response = await woo.get(`products/${id}`);
return response.data;
}
// Get product variations
export async function getProductVariations(productId: number) {
const response = await woo.get(`products/${productId}/variations`, {
per_page: 100,
});
return response.data;
}
Create and manage orders
// lib/orders.ts
interface OrderLineItem {
product_id: number;
variation_id?: number;
quantity: number;
}
interface CreateOrderParams {
billing: {
first_name: string;
last_name: string;
email: string;
address_1: string;
city: string;
postcode: string;
country: string;
};
line_items: OrderLineItem[];
payment_method?: string;
}
export async function createOrder(params: CreateOrderParams) {
const response = await woo.post("orders", {
...params,
status: "pending",
payment_method: params.payment_method ?? "stripe",
payment_method_title: "Credit Card",
set_paid: false,
});
return response.data;
}
export async function updateOrderStatus(
orderId: number,
status: "pending" | "processing" | "on-hold" | "completed" | "cancelled" | "refunded",
note?: string
) {
const updateData: any = { status };
if (note) {
// Add an order note
await woo.post(`orders/${orderId}/notes`, { note });
}
const response = await woo.put(`orders/${orderId}`, updateData);
return response.data;
}
export async function getOrders(params: {
status?: string;
after?: string; // ISO 8601 date
page?: number;
} = {}) {
const response = await woo.get("orders", {
status: params.status ?? "processing",
after: params.after,
per_page: 50,
page: params.page ?? 1,
});
return {
orders: response.data,
totalPages: parseInt(response.headers["x-wp-totalpages"]),
};
}
Manage inventory and product updates
// Update stock quantity for a product or variation
export async function updateStock(productId: number, quantity: number, variationId?: number) {
const endpoint = variationId
? `products/${productId}/variations/${variationId}`
: `products/${productId}`;
const response = await woo.put(endpoint, {
stock_quantity: quantity,
manage_stock: true,
});
return response.data;
}
// Batch update products (up to 100 per request)
export async function batchUpdateProducts(
updates: Array<{ id: number; regular_price?: string; stock_quantity?: number; status?: string }>
) {
const response = await woo.post("products/batch", { update: updates });
return response.data;
}
Examples
Full product sync from external catalog
import pLimit from "p-limit";
export async function syncProductsFromCatalog(
externalProducts: Array<{ sku: string; price: number; stock: number }>
) {
const limit = pLimit(5); // Max 5 concurrent API calls
const results = await Promise.allSettled(
externalProducts.map((ext) =>
limit(async () => {
// Look up WooCommerce product by SKU
const searchResponse = await woo.get("products", { sku: ext.sku });
const existing = searchResponse.data[0];
if (existing) {
// Update existing product
return woo.put(`products/${existing.id}`, {
regular_price: ext.price.toFixed(2),
stock_quantity: ext.stock,
manage_stock: true,
});
} else {
console.warn(`SKU not found in WooCommerce: ${ext.sku}`);
return null;
}
})
)
);
const failed = results.filter((r) => r.status === "rejected");
if (failed.length > 0) {
console.error(`${failed.length} products failed to sync`);
}
return results;
}
Customer management
// Create or update customer
export async function upsertCustomer(email: string, data: Record<string, any>) {
const searchResponse = await woo.get("customers", { email });
const existing = searchResponse.data[0];
if (existing) {
const response = await woo.put(`customers/${existing.id}`, data);
return response.data;
} else {
const response = await woo.post("customers", { email, ...data });
return response.data;
}
}
// Get customer order history
export async function getCustomerOrders(customerId: number) {
const response = await woo.get("orders", {
customer: customerId,
per_page: 50,
orderby: "date",
order: "desc",
});
return response.data;
}
Best Practices
- Always use HTTPS — OAuth 1.0a works over HTTP but transmits credentials with every request; HTTPS + Basic Auth is simpler and safer for server-to-server calls
- Respect rate limits — WordPress doesn't enforce API rate limits by default, but high request volumes can cause PHP-FPM or MySQL exhaustion; use
p-limit or a queue for bulk operations
- Use batch endpoints for bulk updates —
/products/batch accepts up to 100 create/update/delete operations in one request vs. 100 individual requests
- Filter fields with
_fields parameter — ?_fields=id,name,price,stock_quantity reduces response payload significantly for large product lists
- Handle WooCommerce-specific error codes — the API returns
rest_invalid_param, woocommerce_rest_cannot_create, etc. in the error body; parse response.data.code for specific error handling
- Use
after and before date filters for incremental syncs — avoid full catalog re-scans by filtering orders/products modified since last sync using ISO 8601 timestamps
- Store the API URL without trailing slash — the WooCommerce client handles URL construction; a trailing slash in the base URL causes double-slash in endpoints
Common Pitfalls
| Problem |
Solution |
401 Unauthorized despite correct keys |
Verify the site uses HTTPS; over HTTP the client must use OAuth 1.0a, not Basic Auth — set isHttps: false in the client config |
| Products endpoint returns empty array |
Check the user assigned to the API key has the correct capabilities; the default woocommerce_manage_products capability is required |
| Order creation fails with product ID error |
Variable products require variation_id in line_items; passing only product_id for a variable product causes invalid_variation error |
| Pagination headers missing |
The x-wp-total and x-wp-totalpages headers are only present on list endpoints, not single-resource endpoints |
| Batch operation partially fails |
Batch responses include individual errors per item; iterate response.data.update array and check each item for error property |
| Slow response on product listing |
Add ?_fields=id,name,price to reduce payload; also consider enabling persistent object cache (Redis) on the WordPress server |
Related Skills
- @woocommerce-plugin-development
- @woocommerce-subscriptions
- @woocommerce-performance
- @headless-commerce-architecture
- @rest-api-design
Source: finsilabs/awesome-ecommerce-skills — distributed by TomeVault.
1---2name: woocommerce-rest-api3description: Integrate or build headless frontends on WooCommerce using its REST API for products, orders, customers, and coupons with key authentication Use when this capability is needed.4---56# WooCommerce REST API78## Overview910WooCommerce ships a versioned REST API (`/wp-json/wc/v3/`) that exposes products, orders, customers, coupons, and store settings over HTTPS. It uses OAuth 1.0a for non-HTTPS environments and Basic Auth (consumer key/secret) over HTTPS. The official `@woocommerce/woocommerce-rest-api` Node.js client handles authentication automatically and supports the full CRUD surface.1112## When to Use This Skill1314- When building a headless storefront that reads products and categories from WooCommerce15- When integrating WooCommerce with an ERP, CRM, or fulfillment system16- When creating an order management dashboard outside of WordPress Admin17- When syncing inventory between WooCommerce and a warehouse or POS system18- When automating bulk product imports or price updates from an external catalog19- When building a mobile app that needs access to WooCommerce store data2021## Core Instructions22231. **Generate API credentials**2425 In WordPress Admin → WooCommerce → Settings → Advanced → REST API → Add Key:26 - Description: `My Integration`27 - User: (admin user)28 - Permissions: Read/Write2930 This generates a Consumer Key (`ck_xxx`) and Consumer Secret (`cs_xxx`). Store them in environment variables, never in source code.3132 ```bash33 WOOCOMMERCE_URL=https://mystore.com34 WOOCOMMERCE_CONSUMER_KEY=ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx35 WOOCOMMERCE_CONSUMER_SECRET=cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx36 ```37382. **Set up the Node.js client**3940 ```bash41 npm install @woocommerce/woocommerce-rest-api42 ```4344 ```typescript45 // lib/woocommerce.ts46 import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";4748 export const woo = new WooCommerceRestApi({49 url: process.env.WOOCOMMERCE_URL!,50 consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY!,51 consumerSecret: process.env.WOOCOMMERCE_CONSUMER_SECRET!,52 version: "wc/v3",53 axiosConfig: {54 timeout: 15000,55 },56 });57 ```58593. **Query products with filtering and pagination**6061 ```typescript62 // lib/products.ts63 interface ProductQuery {64 page?: number;65 perPage?: number;66 category?: number;67 status?: "publish" | "draft" | "private";68 stockStatus?: "instock" | "outofstock" | "onbackorder";69 orderby?: "date" | "popularity" | "price" | "title";70 }7172 export async function getProducts(params: ProductQuery = {}) {73 const response = await woo.get("products", {74 page: params.page ?? 1,75 per_page: params.perPage ?? 20,76 status: params.status ?? "publish",77 stock_status: params.stockStatus,78 orderby: params.orderby ?? "date",79 category: params.category,80 });8182 return {83 products: response.data,84 totalPages: parseInt(response.headers["x-wp-totalpages"]),85 totalProducts: parseInt(response.headers["x-wp-total"]),86 };87 }8889 export async function getProductById(id: number) {90 const response = await woo.get(`products/${id}`);91 return response.data;92 }9394 // Get product variations95 export async function getProductVariations(productId: number) {96 const response = await woo.get(`products/${productId}/variations`, {97 per_page: 100,98 });99 return response.data;100 }101 ```1021034. **Create and manage orders**104105 ```typescript106 // lib/orders.ts107 interface OrderLineItem {108 product_id: number;109 variation_id?: number;110 quantity: number;111 }112113 interface CreateOrderParams {114 billing: {115 first_name: string;116 last_name: string;117 email: string;118 address_1: string;119 city: string;120 postcode: string;121 country: string;122 };123 line_items: OrderLineItem[];124 payment_method?: string;125 }126127 export async function createOrder(params: CreateOrderParams) {128 const response = await woo.post("orders", {129 ...params,130 status: "pending",131 payment_method: params.payment_method ?? "stripe",132 payment_method_title: "Credit Card",133 set_paid: false,134 });135 return response.data;136 }137138 export async function updateOrderStatus(139 orderId: number,140 status: "pending" | "processing" | "on-hold" | "completed" | "cancelled" | "refunded",141 note?: string142 ) {143 const updateData: any = { status };144 if (note) {145 // Add an order note146 await woo.post(`orders/${orderId}/notes`, { note });147 }148 const response = await woo.put(`orders/${orderId}`, updateData);149 return response.data;150 }151152 export async function getOrders(params: {153 status?: string;154 after?: string; // ISO 8601 date155 page?: number;156 } = {}) {157 const response = await woo.get("orders", {158 status: params.status ?? "processing",159 after: params.after,160 per_page: 50,161 page: params.page ?? 1,162 });163 return {164 orders: response.data,165 totalPages: parseInt(response.headers["x-wp-totalpages"]),166 };167 }168 ```1691705. **Manage inventory and product updates**171172 ```typescript173 // Update stock quantity for a product or variation174 export async function updateStock(productId: number, quantity: number, variationId?: number) {175 const endpoint = variationId176 ? `products/${productId}/variations/${variationId}`177 : `products/${productId}`;178179 const response = await woo.put(endpoint, {180 stock_quantity: quantity,181 manage_stock: true,182 });183 return response.data;184 }185186 // Batch update products (up to 100 per request)187 export async function batchUpdateProducts(188 updates: Array<{ id: number; regular_price?: string; stock_quantity?: number; status?: string }>189 ) {190 const response = await woo.post("products/batch", { update: updates });191 return response.data;192 }193 ```194195## Examples196197### Full product sync from external catalog198199```typescript200import pLimit from "p-limit";201202export async function syncProductsFromCatalog(203 externalProducts: Array<{ sku: string; price: number; stock: number }>204) {205 const limit = pLimit(5); // Max 5 concurrent API calls206207 const results = await Promise.allSettled(208 externalProducts.map((ext) =>209 limit(async () => {210 // Look up WooCommerce product by SKU211 const searchResponse = await woo.get("products", { sku: ext.sku });212 const existing = searchResponse.data[0];213214 if (existing) {215 // Update existing product216 return woo.put(`products/${existing.id}`, {217 regular_price: ext.price.toFixed(2),218 stock_quantity: ext.stock,219 manage_stock: true,220 });221 } else {222 console.warn(`SKU not found in WooCommerce: ${ext.sku}`);223 return null;224 }225 })226 )227 );228229 const failed = results.filter((r) => r.status === "rejected");230 if (failed.length > 0) {231 console.error(`${failed.length} products failed to sync`);232 }233234 return results;235}236```237238### Customer management239240```typescript241// Create or update customer242export async function upsertCustomer(email: string, data: Record<string, any>) {243 const searchResponse = await woo.get("customers", { email });244 const existing = searchResponse.data[0];245246 if (existing) {247 const response = await woo.put(`customers/${existing.id}`, data);248 return response.data;249 } else {250 const response = await woo.post("customers", { email, ...data });251 return response.data;252 }253}254255// Get customer order history256export async function getCustomerOrders(customerId: number) {257 const response = await woo.get("orders", {258 customer: customerId,259 per_page: 50,260 orderby: "date",261 order: "desc",262 });263 return response.data;264}265```266267## Best Practices268269- **Always use HTTPS** — OAuth 1.0a works over HTTP but transmits credentials with every request; HTTPS + Basic Auth is simpler and safer for server-to-server calls270- **Respect rate limits** — WordPress doesn't enforce API rate limits by default, but high request volumes can cause PHP-FPM or MySQL exhaustion; use `p-limit` or a queue for bulk operations271- **Use batch endpoints for bulk updates** — `/products/batch` accepts up to 100 create/update/delete operations in one request vs. 100 individual requests272- **Filter fields with `_fields` parameter** — `?_fields=id,name,price,stock_quantity` reduces response payload significantly for large product lists273- **Handle WooCommerce-specific error codes** — the API returns `rest_invalid_param`, `woocommerce_rest_cannot_create`, etc. in the error body; parse `response.data.code` for specific error handling274- **Use `after` and `before` date filters** for incremental syncs — avoid full catalog re-scans by filtering orders/products modified since last sync using ISO 8601 timestamps275- **Store the API URL without trailing slash** — the WooCommerce client handles URL construction; a trailing slash in the base URL causes double-slash in endpoints276277## Common Pitfalls278279| Problem | Solution |280|---------|----------|281| `401 Unauthorized` despite correct keys | Verify the site uses HTTPS; over HTTP the client must use OAuth 1.0a, not Basic Auth — set `isHttps: false` in the client config |282| Products endpoint returns empty array | Check the user assigned to the API key has the correct capabilities; the default `woocommerce_manage_products` capability is required |283| Order creation fails with product ID error | Variable products require `variation_id` in `line_items`; passing only `product_id` for a variable product causes `invalid_variation` error |284| Pagination headers missing | The `x-wp-total` and `x-wp-totalpages` headers are only present on list endpoints, not single-resource endpoints |285| Batch operation partially fails | Batch responses include individual errors per item; iterate `response.data.update` array and check each item for `error` property |286| Slow response on product listing | Add `?_fields=id,name,price` to reduce payload; also consider enabling persistent object cache (Redis) on the WordPress server |287288## Related Skills289290- @woocommerce-plugin-development291- @woocommerce-subscriptions292- @woocommerce-performance293- @headless-commerce-architecture294- @rest-api-design295296---297> Source: [finsilabs/awesome-ecommerce-skills](https://github.com/finsilabs/awesome-ecommerce-skills) — distributed by [TomeVault](https://tomevault.io).298<!-- tomevault:4.0:skill_md:2026-06-16 -->