npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

woocommerce-rest-ts-api

v7.1.2

Published

WooCommerce REST API - Type Script Library

Readme

Updates Test CI npm npm License: MIT Known Vulnerabilities

WooCommerce REST API - TypeScript Library

A modern, type-safe TypeScript library for the WooCommerce REST API with enhanced error handling, improved type safety, and convenient methods for common operations.

New Features in v7.1.0:

  • 🛡️ Enhanced Error Handling - Custom error classes with detailed error information
  • 🔧 Improved Type Safety - Better response typing with WooCommerceApiResponse<T>
  • 🚀 Convenience Methods - Easy-to-use methods for common operations
  • 📦 Modern Module Support - Full ESM and CJS compatibility
  • 🎯 Better Developer Experience - Comprehensive TypeScript support
  • 🔧 Fixed Configuration Issues - Resolved TypeScript and ESLint compatibility problems
  • 📝 Updated Dependencies - Latest TypeScript 5.8.3 and modern tooling

New TypeScript library for WooCommerce REST API. Supports CommonJS (CJS) and ECMAScript (ESM)

🚀 Key Features

  • Type-Safe: Full TypeScript support with comprehensive type definitions
  • Modern: ES2020+ with async/await support
  • Flexible: Support for both CommonJS and ES modules
  • Secure: Built-in OAuth 1.0a authentication
  • Error Handling: Custom error classes with detailed error information
  • Convenience Methods: Easy-to-use methods for common operations
  • Lightweight: Minimal dependencies with tree-shaking support

🔧 Installation

npm install --save woocommerce-rest-ts-api

📚 Getting Started

Generate API credentials (Consumer Key & Consumer Secret) following this instructions http://docs.woocommerce.com/document/woocommerce-rest-api/.

Check out the WooCommerce API endpoints and data that can be manipulated in http://woocommerce.github.io/woocommerce-rest-api-docs/.

⚙️ Setup

ESM Example:

import WooCommerceRestApi, { WooRestApiOptions } from "woocommerce-rest-ts-api";

const options: WooRestApiOptions = {
    url: "https://your-store.com",
    consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    version: "wc/v3",
    queryStringAuth: false // Force Basic Authentication as query string when using HTTPS
};

const api = new WooCommerceRestApi(options);

CJS Example:

const WooCommerceRestApi = require("woocommerce-rest-ts-api").default;

const api = new WooCommerceRestApi({
  url: "https://your-store.com",
  consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  version: "wc/v3",
  queryStringAuth: false
});

🔧 Configuration Options

| Option | Type | Required | Description | |-------------------|-----------|----------|---------------------------------------------------------------------------------------------------------------------| | url | String | yes | Your Store URL, example: https://your-store.com | | consumerKey | String | yes | Your API consumer key | | consumerSecret | String | yes | Your API consumer secret | | wpAPIPrefix | String | no | Custom WP REST API URL prefix, used to support custom prefixes created with the rest_url_prefix filter | | version | String | no | API version, default is wc/v3 | | encoding | String | no | Encoding, default is 'utf-8' | | queryStringAuth | Bool | no | When true and using under HTTPS force Basic Authentication as query string, default is false | | port | string | no | Provide support for URLs with ports, eg: 8080 | | timeout | Integer | no | Define the request timeout | | axiosConfig | Object | no | Define the custom Axios config, also override this library options |

🎯 Enhanced Response Type

All API methods now return a WooCommerceApiResponse<T> object with the following structure:

interface WooCommerceApiResponse<T> {
    data: T;           // The actual response data
    status: number;    // HTTP status code
    statusText: string; // HTTP status text
    headers: any;      // Response headers
}

🛡️ Error Handling

The library now includes enhanced error handling with custom error classes:

import { WooCommerceApiError, AuthenticationError } from "woocommerce-rest-ts-api";

try {
    const products = await api.getProducts();
} catch (error) {
    if (error instanceof WooCommerceApiError) {
        console.error('API Error:', error.message);
        console.error('Status Code:', error.statusCode);
        console.error('Endpoint:', error.endpoint);
        console.error('Response:', error.response);
    } else if (error instanceof AuthenticationError) {
        console.error('Authentication failed:', error.message);
    }
}

📖 API Methods

Core Methods

GET Request

const response = await api.get<ProductType[]>("products", { per_page: 10 });

POST Request

const response = await api.post<ProductType>("products", productData);

PUT Request

const response = await api.put<ProductType>("products", updateData, { id: 123 });

DELETE Request

const response = await api.delete<ProductType>("products", { force: true }, { id: 123 });

OPTIONS Request

const response = await api.options("products");

🚀 Convenience Methods

Products

// Get all products with type safety
const products = await api.getProducts({ per_page: 20, status: 'publish' });

// Get a single product
const product = await api.getProduct(123);

// Create a new product
const newProduct = await api.createProduct({
    name: "New Product",
    type: "simple",
    regular_price: "29.99"
});

// Update a product
const updatedProduct = await api.updateProduct(123, {
    name: "Updated Product Name"
});

Orders

// Get all orders
const orders = await api.getOrders({ status: 'processing' });

// Get a single order
const order = await api.getOrder(123);

// Create a new order
const newOrder = await api.createOrder({
    payment_method: "bacs",
    billing: {
        first_name: "John",
        last_name: "Doe",
        // ... other billing details
    },
    line_items: [
        {
            product_id: 93,
            quantity: 2
        }
    ]
});

Customers

// Get all customers
const customers = await api.getCustomers();

// Get a single customer
const customer = await api.getCustomer(123);

Other Endpoints

// Get coupons
const coupons = await api.getCoupons();

// Get system status
const systemStatus = await api.getSystemStatus();

💡 Usage Examples

Complete Product Management Example

import WooCommerceRestApi, { 
    WooRestApiOptions, 
    Products, 
    WooCommerceApiError 
} from "woocommerce-rest-ts-api";

const api = new WooCommerceRestApi({
    url: "https://your-store.com",
    consumerKey: "ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    consumerSecret: "cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    version: "wc/v3"
});

async function manageProducts() {
    try {
        // List products with pagination
        const products = await api.getProducts({
            per_page: 20,
            page: 1,
            status: 'publish'
        });
        
        console.log(`Found ${products.data.length} products`);
        console.log(`Total pages: ${products.headers['x-wp-totalpages']}`);
        
        // Create a new product
        const newProduct = await api.createProduct({
            name: "Premium Quality Product",
            type: "simple",
            regular_price: "29.99",
            description: "A premium quality product description",
            short_description: "Premium quality product",
            categories: [{ id: 9 }],
            images: [{
                src: "https://example.com/image.jpg"
            }]
        });
        
        console.log(`Created product with ID: ${newProduct.data.id}`);
        
        // Update the product
        const updatedProduct = await api.updateProduct(newProduct.data.id, {
            regular_price: "39.99",
            sale_price: "34.99"
        });
        
        console.log(`Updated product price to: ${updatedProduct.data.regular_price}`);
        
    } catch (error) {
        if (error instanceof WooCommerceApiError) {
            console.error(`API Error: ${error.message} (Status: ${error.statusCode})`);
        } else {
            console.error('Unexpected error:', error);
        }
    }
}

manageProducts();

Order Management Example

async function manageOrders() {
    try {
        // Get recent orders
        const orders = await api.getOrders({
            status: 'processing',
            orderby: 'date',
            order: 'desc',
            per_page: 10
        });
        
        console.log(`Found ${orders.data.length} processing orders`);
        
        // Create a new order
        const newOrder = await api.createOrder({
            payment_method: "bacs",
            payment_method_title: "Direct Bank Transfer",
            set_paid: true,
            billing: {
                first_name: "John",
                last_name: "Doe",
                address_1: "969 Market",
                city: "San Francisco",
                state: "CA",
                postcode: "94103",
                country: "US",
                email: "[email protected]",
                phone: "555-555-5555"
            },
            line_items: [
                {
                    product_id: 93,
                    quantity: 2
                }
            ]
        });
        
        console.log(`Created order with ID: ${newOrder.data.id}`);
        
    } catch (error) {
        if (error instanceof WooCommerceApiError) {
            console.error(`Order creation failed: ${error.message}`);
        }
    }
}

🔍 Type Definitions

The library includes comprehensive TypeScript definitions for all WooCommerce entities:

  • Products - Product data structure
  • Orders - Order data structure
  • Customers - Customer data structure
  • Coupons - Coupon data structure
  • SystemStatus - System status data structure
  • And many more...

🐛 Error Types

  • WooCommerceApiError - General API errors with status codes and response data
  • AuthenticationError - Authentication-specific errors
  • OptionsException - Configuration/setup errors

🏗️ Migration from Previous Versions

If you're upgrading from an earlier version, note these changes:

From v7.0.x to v7.1.0

  • No Breaking Changes: v7.1.0 is fully backward compatible
  • Improved Stability: Better build process and dependency management
  • Enhanced Tooling: Updated TypeScript and ESLint configurations

From v6.x and earlier

  1. Response Structure: All methods now return WooCommerceApiResponse<T> instead of raw Axios responses
  2. Error Handling: New custom error classes replace generic errors
  3. Convenience Methods: New methods like getProducts(), getOrders() etc. are available
  4. Type Safety: Better TypeScript support with generic types

📊 Changelog

v7.1.0 (Latest)

  • ✨ Added enhanced error handling with custom error classes
  • 🔧 Improved type safety with WooCommerceApiResponse<T>
  • 🚀 Added convenience methods for common operations
  • 📦 Fixed TypeScript configuration issues and ESLint compatibility
  • 🛡️ Better input validation and error messages
  • 🔧 Resolved build and publishing pipeline issues
  • 📝 Updated to TypeScript 5.8.3 with latest dependencies
  • 🎯 Improved developer experience with better tooling

See full changelog

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Thanks / Credits

📞 Support & Contact

If you need help or have questions, please:

  1. Check the WooCommerce REST API Documentation
  2. Open an issue on GitHub
  3. Contact via email (use subject: "WooCommerce TS Library - [Your Issue]")

| Name | Email | |-------|--------| | Yuri Lima | [email protected] |


Made with ❤️ by Yuri Lima