Lesson 7.1. WC REST API

Goal

Work with WC REST API v3: keys, permissions, pagination, batch operations and custom endpoints.

Key concepts

  • Base path /wp-json/wc/v3/ — products, orders, customers, coupons, reports
  • API keys: consumer key / secret with read, write or read_write permissions; HTTPS only
  • Pagination: per_page (up to 100), page, the X-WP-Total and X-WP-TotalPages headers
  • Batch operations: /products/batch — create, update, delete in one request
  • A custom endpoint: register_rest_route() with a permission_callback and a capability check
  • The response is extended with the woocommerce_rest_prepare_{object}_object filters

Diagram

flowchart LR
  ERP["ERP / CRM / mobile app"] -->|"Basic auth: ck / cs<br/>HTTPS"| API["/wc/v3"]
  API --> PERM{"Key permissions<br/>+ user capability"}
  PERM --> CRUD["CRUD: WC_Product, WC_Order"]
  CRUD --> DB[("Database")]

Code

Update the stock of 3 products in one request:

BASH
curl -X POST https://shop.test/wp-json/wc/v3/products/batch \
  -u ck_xxx:cs_xxx \
  -H "Content-Type: application/json" \
  -d '{"update":[{"id":31,"stock_quantity":12},{"id":32,"stock_quantity":0},{"id":33,"stock_quantity":40}]}'

A custom endpoint with permissions:

PHP
<?php
add_action( 'rest_api_init', static function () {
	register_rest_route( 'my-shop/v1', '/low-stock', [
		'methods'             => 'GET',
		'permission_callback' => static fn () => current_user_can( 'manage_woocommerce' ),
		'args'                => [ 'threshold' => [ 'type' => 'integer', 'default' => 5, 'minimum' => 0 ] ],
		'callback'            => static function ( WP_REST_Request $request ) {
			$products = wc_get_products( [
				'limit'        => 100,
				'stock_status' => 'instock',
				'return'       => 'objects',
			] );
			$low = array_filter( $products, static fn ( WC_Product $p ) =>
				$p->managing_stock() && $p->get_stock_quantity() <= $request['threshold'] );
			return array_values( array_map( static fn ( WC_Product $p ) => [
				'id'  => $p->get_id(),
				'sku' => $p->get_sku(),
				'qty' => $p->get_stock_quantity(),
			], $low ) );
		},
	] );
} );

// WooCommerce authenticates ck/cs keys only on its own namespaces (wc/…, wc-…).
// Without this filter a request with a key to my-shop/v1 is anonymous → 401.
add_filter( 'woocommerce_rest_is_request_to_rest_api', static function ( bool $is_wc ): bool {
	$uri = esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
	return $is_wc || str_contains( $uri, '/' . rest_get_url_prefix() . '/my-shop/' );
} );

Common mistakes

SymptomCauseFix
401 over HTTP on stagingBasic auth with keys works only over HTTPSHTTPS, or OAuth 1.0a for HTTP (not recommended)
The integration sees only 10 ordersDefault paginationper_page and paging through X-WP-TotalPages
The endpoint is open to everyonepermission_callback => __return_trueA capability check
A custom endpoint returns 401 even with a valid keyWooCommerce authenticates keys only on wc/ and wc- namespacesThe woocommerce_rest_is_request_to_rest_api filter for your namespace

Weak and strong answer

Question: How do you give an ERP access to orders?

Weak answer. Create an API key with read_write permissions.

Strong answer. A separate integration user with a minimal role, a key with only the permissions it needs (often read for orders and write only for stock), HTTPS only. The key lives in the ERP's secrets, not in code. For large volumes — batch operations and pagination. If the standard endpoint isn't enough — a custom one with a permission_callback.

Why the second is stronger: The principle of least privilege, key security and handling volume.

Practice

In the terminal: get the orders of the last day page by page with the read-only "ERP" key. Try to update stock with this key, then with the separate write key. Check the low-stock endpoint without a key and with one.

On your own site: create a read-only API key for an "ERP" user and your own low-stock endpoint with the code above.

curl / wp — Module 7. APIs and Integrations

Interview Questions

Consumer key / secret through Basic auth over HTTPS. For requests from your own site (admin, blocks) — a cookie + the wp_rest nonce.

Page through with per_page=100 following X-WP-TotalPages, or filter by date (modified_after) and sync incrementally.

The woocommerce_rest_prepare_shop_order_object filter or register_rest_field() for the matching type.

Save your progress

Sign in or create a free account to mark lessons as completed and continue the whole course. You will come back to this lesson.