Complete WooCommerce REST API guide: generate API keys, authenticate with OAuth or Basic Auth, query endpoints, and integrate JavaScript or PHP. This practical guide covers step-by-step setup, real-world code snippets, security hardening, and common production edge cases.
Introduction
The WooCommerce REST API gives you programmatic access to nearly every part of your store — products, orders, customers, coupons, shipping zones, and more. Whether you're building a custom dashboard, syncing inventory with a third-party system, or automating order processing, the WooCommerce REST API is your bridge.
In this guide you'll learn how to:
- Generate and use API keys securely
- Authenticate using OAuth 1.0a and Basic Auth
- Query products, orders, and customers
- Create and update records
- Handle pagination and filtering
- Use the official JavaScript library
Prerequisites
- A WooCommerce store running WordPress 5.6+ and WooCommerce 6.0+
- HTTPS enabled on your domain (required for Basic Auth)
- Node.js 18+ for the JavaScript examples
1. Enable the WooCommerce REST API
The API is enabled by default in WooCommerce. To verify:
- Go to WooCommerce → Settings → Advanced → REST API
- Click Add key
- Set Description, User (admin user), and Permissions (Read/Write)
- Click Generate API key
- Save your Consumer Key and Consumer Secret — these are shown only once
2. Authentication Methods
Basic Auth (HTTPS only — recommended for server-side)
const consumerKey = 'ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const consumerSecret = 'cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const base = Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64');
const res = await fetch('https://yourstore.com/wp-json/wc/v3/products', {
headers: { Authorization: `Basic ${base}` },
});
const products = await res.json();
Using the Official @woocommerce/woocommerce-rest-api Package
npm install @woocommerce/woocommerce-rest-api
import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api';
const api = new WooCommerceRestApi({
url: 'https://yourstore.com',
consumerKey: 'ck_xxxxxxxxxxxx',
consumerSecret: 'cs_xxxxxxxxxxxx',
version: 'wc/v3',
});
This library handles OAuth signing automatically, making it safe for both HTTP and HTTPS.
3. Working with Products
List All Products
const { data: products } = await api.get('products', {
per_page: 20,
page: 1,
status: 'publish',
});
products.forEach(product => {
console.log(product.id, product.name, product.price);
});
Get a Single Product
const { data: product } = await api.get('products/123');
console.log(product.name, product.stock_quantity);
Create a Product
const { data: newProduct } = await api.post('products', {
name: 'Premium T-Shirt',
type: 'simple',
regular_price: '29.99',
description: 'A high-quality premium t-shirt.',
short_description: 'Comfortable and stylish.',
categories: [{ id: 9 }],
images: [{ src: 'https://example.com/image.jpg' }],
});
console.log('Created:', newProduct.id);
Update a Product
const { data: updated } = await api.put('products/123', {
regular_price: '24.99',
stock_quantity: 50,
manage_stock: true,
});
Delete a Product
await api.delete('products/123', { force: true }); // force=true skips trash
4. Working with Orders
List Recent Orders
const { data: orders } = await api.get('orders', {
per_page: 10,
status: 'processing',
orderby: 'date',
order: 'desc',
});
orders.forEach(order => {
console.log(`Order #${order.number} — ${order.status} — $${order.total}`);
});
Get Order Details
const { data: order } = await api.get('orders/456');
console.log('Customer:', order.billing.first_name, order.billing.last_name);
console.log('Email:', order.billing.email);
console.log('Items:');
order.line_items.forEach(item => {
console.log(` ${item.name} x${item.quantity} — $${item.total}`);
});
Update Order Status
await api.put('orders/456', { status: 'completed' });
Create a Manual Order
const { data: order } = await api.post('orders', {
payment_method: 'bacs',
payment_method_title: 'Direct Bank Transfer',
set_paid: true,
billing: {
first_name: 'John',
last_name: 'Doe',
email: 'john@example.com',
address_1: '123 Main St',
city: 'Chennai',
country: 'IN',
},
line_items: [
{ product_id: 123, quantity: 2 },
],
});
5. Working with Customers
List Customers
const { data: customers } = await api.get('customers', {
per_page: 50,
role: 'customer',
});
Search by Email
const { data: customers } = await api.get('customers', {
email: 'john@example.com',
});
Create a Customer
const { data: customer } = await api.post('customers', {
email: 'jane@example.com',
first_name: 'Jane',
last_name: 'Smith',
username: 'jane_smith',
password: 'SecurePassword123!',
billing: {
first_name: 'Jane',
last_name: 'Smith',
email: 'jane@example.com',
country: 'IN',
},
});
6. Pagination and Filtering
WooCommerce API responses include pagination headers:
const response = await api.get('products', { per_page: 10, page: 1 });
// Total items and pages from headers
const totalItems = response.headers['x-wp-total'];
const totalPages = response.headers['x-wp-totalpages'];
console.log(`${totalItems} products across ${totalPages} pages`);
Fetching All Products (Auto-paginate)
async function getAllProducts() {
let page = 1;
let allProducts = [];
while (true) {
const response = await api.get('products', { per_page: 100, page });
allProducts = [...allProducts, ...response.data];
if (page >= parseInt(response.headers['x-wp-totalpages'])) break;
page++;
}
return allProducts;
}
7. Filtering Products
// Products in a specific category
const { data } = await api.get('products', { category: '15' });
// On sale products
const { data: onSale } = await api.get('products', { on_sale: true });
// Products above a price
const { data: expensive } = await api.get('products', {
min_price: '100',
max_price: '500',
});
// Search by name
const { data: results } = await api.get('products', { search: 'shirt' });
8. Error Handling
try {
const { data } = await api.get('products/999999');
} catch (error) {
if (error.response) {
const { status, data } = error.response;
console.error(`API Error ${status}:`, data.message, data.code);
} else {
console.error('Network error:', error.message);
}
}
Common error codes:
| Code | Meaning |
|---|---|
woocommerce_rest_cannot_view | Invalid or missing credentials |
woocommerce_rest_product_invalid_id | Product not found |
rest_no_route | Endpoint does not exist |
9. Rate Limiting and Performance
WooCommerce itself doesn't enforce rate limits, but your server (Nginx/Apache) or hosting provider might. Best practices:
- Batch updates using the
batchendpoint instead of individual PUT calls - Cache responses on your end for read-heavy operations
- Use webhooks for real-time updates instead of polling
Batch Update Example
const { data } = await api.post('products/batch', {
update: [
{ id: 1, regular_price: '15.99' },
{ id: 2, regular_price: '22.99' },
{ id: 3, stock_quantity: 0 },
],
});
Conclusion
The WooCommerce REST API is well-documented and comprehensive. Once you have your API keys configured, you can:
- Build custom admin dashboards outside WordPress
- Sync inventory with ERP systems in real-time
- Process orders from external platforms
- Automate customer communication workflows
- Connect your store to marketplaces like Amazon or Etsy
The next step is exploring WooCommerce Webhooks — which let your store push data to external services automatically when orders, products, or customers change.
Continue Exploring Our WooCommerce Series
- WooCommerce REST API: Managing Orders and Inventory — Complete order fulfillment lifecycle via API.
- WooCommerce Webhooks Integration Guide — Trigger automated workflows on order creation.
- WooCommerce Custom REST Endpoints (Under 50ms) — Bypass heavy core payloads in custom plugins.
- WooCommerce Product Sync via REST API — Sync external ERP catalogues to WooCommerce.
- Integrating Stripe with WooCommerce via REST API — Custom payment intents and webhook handling.
Frequently Asked Questions (WooCommerce REST API)
How do I generate WooCommerce REST API keys safely?
Navigate to WooCommerce → Settings → Advanced → REST API, click Add key, assign a user with minimal required capabilities (Read, Write, or Read/Write), and store the Consumer Key and Consumer Secret strictly inside server-side .env variables—never expose keys in client-side browser bundles.
Which WooCommerce REST API authentication method should I use?
Use HTTPS Basic Auth for server-to-server requests (Next.js API routes, Node.js workers, Python scripts) and OAuth 1.0a via @woocommerce/woocommerce-rest-api when integrating over unencrypted development transports.
Why does /wp-json/wc/v3/products return a 401 or 404 error?
A 404 usually means WordPress Pretty Permalinks are set to Plain (switch to Post name under Settings → Permalinks), whereas 401 typically occurs when Apache/Nginx strips the Authorization header or SSL is misconfigured.
Written by Dev Pattern LabsCore Engineering
Dev Pattern Labs is an engineering lab and digital consultancy specializing in custom Next.js web applications, WooCommerce REST API integrations, and workflow automation for growing businesses.
Recommended Companion Articles

WooCommerce Abandoned Cart Recovery via REST API and Webhooks
Recover lost revenue with automated WooCommerce cart recovery. Capture draft checkouts via webhooks, generate restore tokens, and send dynamic emails.

Building High-Performance Custom Endpoints in WooCommerce REST API
Create lightweight WP_REST_Controller endpoints in WooCommerce. Bypass heavy core payloads, reduce database queries, and return JSON responses under 50ms.

Building Headless WooCommerce Cart and Checkout in Next.js 15
Architect a high-converting headless WooCommerce cart and checkout flow with Next.js 15 App Router, CoCart REST endpoints, and Stripe payment elements.
