Skip to main content

WooCommerce Store API

The Store API provides public Rest API endpoints for the development of customer-facing cart, checkout, and product functionality. It follows many of the patterns used in the WordPress REST API.

In contrast to the WooCommerce REST API, the Store API is unauthenticated and does not provide access to sensitive store data or other customer information.

Example of a valid API request using cURL:

curl "https://example-store.com/wp-json/wc/store/v1/products"

Possible uses of the Store API include:

  1. Obtaining a list of products to display that can be searched or filtered
  2. Adding products to the cart and returning an updated cart object for display
  3. Obtaining shipping rates for a cart
  4. Converting a customer’s cart to an Order, collecting addresses, and then facilitating payment

Requirements and limitations​

  • This is an unauthenticated API. It does not require API keys or authentication tokens for access.
  • All API responses return JSON-formatted data.
  • Data returned from the API is reflective of the current user (customer). Customer sessions in WooCommerce are cookie-based.
  • Store API cannot be used to look up other customers and orders by ID; only data belonging to the current user.
  • Likewise, Store API cannot be used to write store data e.g. settings. For more extensive access, use the authenticated WC REST API.
  • Endpoints that do allow writes, for example, updating the current customer address, require a nonce-token.
  • Store API is render-target agnostic and should not make assumptions about where content will be displayed. For example, returning HTML would be discouraged unless the data type itself is HTML.

Store API Namespace​

Resources in the Store API are all found within the wc/store/v1 namespace, and since this API extends the WordPress API, accessing it requires the /wp-json/ base. Currently, the only version is v1. If the version is omitted, v1 will be served.

Examples:

GET /wp-json/wc/store/v1/products
GET /wp-json/wc/store/v1/cart

The API uses JSON to serialize data. You don’t need to specify .json at the end of an API URL.

Resources and endpoints​

Available resources in the Store API are listed below, with links to more detailed documentation.

ResourceMethodsEndpoints
CartGET/wc/store/v1/cart
POST/wc/store/v1/cart/add-item
POST/wc/store/v1/cart/remove-item
POST/wc/store/v1/cart/update-item
POST/wc/store/v1/cart/apply-coupon
POST/wc/store/v1/cart/remove-coupon
POST/wc/store/v1/cart/update-customer
POST/wc/store/v1/cart/select-shipping-rate
Cart ItemsGET, POST, DELETE/wc/store/v1/cart/items
GET, POST, PUT, DELETE/wc/store/v1/cart/items/:key
Cart CouponsGET, POST, DELETE/wc/store/v1/cart/coupons
GET, DELETE/wc/store/v1/cart/coupon/:code
CheckoutGET, POST, PUT/wc/store/v1/checkout
Checkout orderPOST/wc/store/v1/checkout/:id
OrderGET/wc/store/v1/order/:id
ProductsGET/wc/store/v1/products
GET/wc/store/v1/products/:id
Product Collection DataGET/wc/store/v1/products/collection-data
Product AttributesGET/wc/store/v1/products/attributes
GET/wc/store/v1/products/attributes/:id
Product Attribute TermsGET/wc/store/v1/products/attributes/:id/terms
Product CategoriesGET/wc/store/v1/products/categories
Product BrandsGET/wc/store/v1/products/brands
Product ReviewsGET/wc/store/v1/products/reviews
Product TagsGET/wc/store/v1/products/tags

Pagination​

If collections contain many results, they may be paginated. When listing resources you can pass the following parameters:

ParameterDescription
pageCurrent page of the collection. Defaults to 1.
per_pageMaximum number of items to be returned in result set. Defaults to 10. Maximum 100.

In the example below, we list 20 products per page and return page 2.

curl "https://example-store.com/wp-json/wc/store/v1/products?page=2&per_page=20"

Additional pagination headers are also sent back with extra information.

HeaderDescription
X-WP-TotalThe total number of items in the collection.
X-WP-TotalPagesThe total number of pages in the collection.
LinkContains links to other pages; next, prev, and up where applicable.

Status codes​

The following table gives an overview of how the API functions generally behave.

Request typeDescription
GETAccess one or more resources and return 200 OK and the result as JSON.
POSTReturn 201 Created if the resource is successfully created and return the newly created resource as JSON.
PUTReturn 200 OK if the resource is modified successfully. The modified result is returned as JSON.
DELETEReturns 204 No Content if the resource was deleted successfully.

The following table shows the possible return codes for API requests.

Response codeDescription
200 OKThe request was successful, the resource(s) itself is returned as JSON.
204 No ContentThe server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
201 CreatedThe POST request was successful and the resource is returned as JSON.
400 Bad RequestA required attribute of the API request is missing.
403 ForbiddenThe request is not allowed.
404 Not FoundA resource could not be accessed, for example it doesn't exist.
405 Method Not AllowedThe request is not supported.
409 ConflictThe request could not be completed due to a conflict with the current state of the target resource. The current state may also be returned.
500 Server ErrorWhile handling the request something went wrong server-side.

Contributing​

There are 3 main parts to each route in the Store API:

  1. Route - Responsible for mapping requests to endpoints. Routes in the Store API extend the AbstractRoute class; this class contains shared functionality for handling requests and returning JSON responses. Routes ensure a valid response is returned and handle collections, errors, and pagination.
  2. Schema - Routes do not format resources. Instead we use Schema classes that represent each type of resource, for example, a Product, a Cart, or a Cart Item. Schema classes in the Store API should extend the AbstractSchema class.
  3. Utility - In more advanced cases where the Store API needs to access complex data from WooCommerce core, or where multiple routes need access to the same data, routes should use a Controller or Utility class. For example, the Store API has an Order Controller and a Cart Controller for looking up order and cart data respectfully.

Typically, routes handle the following types of requests:

  • GET requests to read product, cart, or checkout data.
  • POST and PUT requests to update cart and checkout data.
  • DELETE requests to remove cart data.
  • OPTIONS requests to retrieve the JSON schema for the current route.

Please review the Store API Guiding principles. This covers our approach to development, and topics such as versioning, what data is safe to include, and how to build new routes.

Extensibility​

The approach to extensibility within the Store API is to expose certain routes and schema to the ExtendSchema class. Documentation for contributors on this can be found here.

If a route includes the extensibility interface, 3rd party developers can use the shared ExtendSchema::class instance to register additional endpoint data and additional schema.

This differs from the traditional filter hook approach in that it is more limiting, but it reduces the likelihood of a 3rd party extension breaking routes and endpoints or overwriting returned data which other apps may rely upon.

If new schema is required, and any of the following statements are true, choose to extend the Store API rather than introducing new schema to existing Store API schemas:

  • The data is part of an extension, not core
  • The data is related to a resource, but not technically part of it
  • The data is difficult to query (performance wise) or has a very narrow or niche use-case

If the data is sensitive (for example, a core setting that should be private), or not related to the current user (for example, looking up an order by order ID), choose to use the authenticated WC REST API.

If you're looking to add new routes and endpoints, rather than extending the Store API schema, extending the Store API is not necessary. You can instead utilize core WordPress functionality to create new routes, choosing to use the same pattern of Store API if you wish. See:

Accessing the customer's cart from a custom route​

WooCommerce doesn't load the cart for REST requests outside the Store API, so WC()->cart is null in a route registered with register_rest_route(). Load it in your callback before using it:

add_action(
'rest_api_init',
function () {
register_rest_route(
'my-extension/v1',
'/cart-summary',
array(
'methods' => 'GET',
'permission_callback' => function () {
if ( ! is_user_logged_in() && wp_validate_auth_cookie( '', 'logged_in' ) ) {
return new WP_Error( 'rest_cookie_invalid_nonce', 'Send a valid X-WP-Nonce header.', array( 'status' => 403 ) );
}

return true;
},
'callback' => function () {
if ( ! function_exists( 'wc_load_cart' ) ) {
return new WP_Error( 'cart_unavailable', 'WooCommerce is not active.', array( 'status' => 503 ) );
}

wc_load_cart();
WC()->cart->get_cart();
WC()->cart->calculate_totals();

$response = new WP_REST_Response(
array(
'items_count' => WC()->cart->get_cart_contents_count(),
'total' => WC()->cart->get_total( 'edit' ),
)
);
$response->header( 'Cache-Control', 'no-store, private' );

return $response;
},
)
);
}
);

wc_load_cart() sets up the session and an empty cart. It doesn't read the cart items, so call WC()->cart->get_cart() next, which loads the items and totals from the session. Then call calculate_totals(), because the stored totals can be out of date. Nothing re-checks them on load, so they go stale when a price, tax rate, shipping rate or coupon changed since the cart was last updated. After that, other cart methods such as get_cart_contents() and get_total() return the customer's cart.

The response is different for every customer, so the example sends Cache-Control: no-store, private. WordPress only sends no-cache headers for logged-in users, and a page cache could otherwise serve one guest's cart to another.

The session is read from the customer's cookies, so call the route from the browser with credentials: 'same-origin'. Also send an X-WP-Nonce header created with wp_create_nonce( 'wp_rest' ). WordPress handles the nonce in two ways:

  • If the nonce is invalid, WordPress rejects the request with a rest_cookie_invalid_nonce error before your callbacks run.
  • If no nonce is sent, WordPress runs the request as a guest, even when the customer is logged in. Loading the cart as a guest would discard the customer's session, so the example's permission callback rejects a request that has a logged-in cookie but no nonce.

Guests don't need a nonce, but WordPress checks any nonce that is sent. A stale nonce, for example from a cached page, gets a 403 for guests too. That response doesn't include a refreshed nonce, so check response.ok before reading the body.

The Store API Nonce and Cart-Token headers only work on Store API routes.

Pass the route URL and the initial nonce to your script from PHP, so the URL works on any install layout:

wp_add_inline_script(
'my-extension-script',
'const myExtension = ' . wp_json_encode(
array(
'cartSummaryUrl' => esc_url_raw( rest_url( 'my-extension/v1/cart-summary' ) ),
'restNonce' => wp_create_nonce( 'wp_rest' ),
)
) . ';',
'before'
);
let restNonce = myExtension.restNonce;

async function getCartSummary() {
const response = await fetch( myExtension.cartSummaryUrl, {
credentials: 'same-origin',
headers: { 'X-WP-Nonce': restNonce },
} );

// Each response carries a refreshed nonce. Use it for the next request instead of the initial one.
restNonce = response.headers.get( 'X-WP-Nonce' ) || restNonce;

if ( ! response.ok ) {
throw new Error( `Cart summary request failed with status ${ response.status }.` );
}

return response.json();
}