A Quick Guide on WooCommerce REST API

Are you looking to interact with the WooCommerce REST API? WooCommerce provides a REST API that will get you real-time data from the backend that can place anywhere on your external application. Through its REST API, one can manage their WooCommerce data by hitting the endpoints. In this article, we study how to use WooCommerce REST API and send HTTP requests to WooCommerce.

If you want to build your own store then you can use WooCommerce as the backend for managing your products, product images, gallery, etc. And then using the REST API, fetch the product data and display it on your external application. WooCommerce provides a REST API documentation for interacting with the backend. Here you will get the details about everything like products, customers, orders, taxes, etc. In this article, we are going to interact with the Product endpoints. In a similar way, you can integrate other options like customers, orders, etc.

Get Your Consumer Key and Consumer Secret

In order to get started with WooCommerce REST API you first need to get your consumer key and consumer secret. These keys are the identification for the store and necessary while giving an API call to WooCommerce.

You must install WooCommerce on your WordPress backend. Then head over to the WooCommerce->Settings page. Click on the Advanced tab and then on the REST API link.

woo rest api

On this page click on the button ‘Create an API Key’.

woo rest api

Enter the description, choose ‘Read/Write’ permissions, and hit the Generate API key button. You can choose Read permission also. It depends on your requirement. If you just need to read data from WooCommerce then choose the ‘Read’ option. And if you want to do both reads and write operations then your option would be ‘Read/Write’.

woo rest api

Copy your consumer key and consumer secret which will be required while giving API calls.

woo rest api

Interact with the WooCommerce REST API

Once you are ready with your consumer key and consumer secret, we can start with the code which interacts with the WooCommerce. As we need to send HTTP requests, install the Guzzle library using the command below.

composer require guzzlehttp/guzzle

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

Now let’s take some endpoints like get all products, get a single product, update a product, and integrate it.

Get Products

While calling the WooCommerce API endpoints, you need to set Authorization header which is a base64 encoded string of your consumer key and consumer secret.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

define('WC_CONSUMER_KEY', 'PASTE_CONSUMER_KEY');
define('WC_CONSUMER_SECRET', 'PASTE_CONSUMER_SECRET');
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'YOUR_DOMAIN_BASE_URL',
]);

try {
    $response = $client->request('GET', '/wp-json/wc/v3/products', [
        'headers' => [
            "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
        ],
        'query' => [
            'per_page' => 18,
        ],
        'verify' => false, //only needed if you are facing SSL certificate issue
    ]);
    
    $body = $response->getBody();
    $arr_body = json_decode($body);
    print_r($arr_body);
} catch (Exception $e) {
    echo $e->getMessage();
}

In the above code, I have called the endpoint which gives a list of products. Here, I have passed 18 as a ‘per_page’ value which will give 18 product’s data in response. You can pass this value as per your requirement. Make sure to replace the placeholders with the actual values before hitting the endpoint.

Get a Single Product

If you want to fetch a single product’s data then your endpoint will be as follows.

$response = $client->request('GET', '/wp-json/wc/v3/products/PRODUCT_ID_HERE', [
    'headers' => [
        "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
    ],
    'verify' => false,
]);

Update a Product

You can update a product by sending a PUT request to the API endpoint. Let’s say you want to update a regular_price of your product.

$response = $client->request('PUT', '/wp-json/wc/v3/products/PRODUCT_ID_HERE', [
    'headers' => [
        "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
    ],
    'json' => [
        'regular_price' => '12.20',
    ],
    'verify' => false,
]);

These are some basic calls. In the same way, the user can send HTTP request for Customers, Orders, Coupons, etc. You can read more about it on their official documentation.

Interact with the WooCommerce REST API using JavaScript

WooCommerce releases their own JavaScript library which is useful to send API call to WooCommerce from JavaScript framework. Let’s say you want to interact with the REST API from your React-based application.

In that case, install the ‘@woocommerce/woocommerce-rest-api’ library by the command:

npm install --save @woocommerce/woocommerce-rest-api

Next in your React component, you can get the list of products using the below code.

import React from 'react';
import ReactDOM from 'react-dom';
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

class ProductsComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: []
    };
  }

  componentDidMount() {
    const api = new WooCommerceRestApi({
      url: "YOUR_DOMAIN_BASE_URL",
      consumerKey: "PASTE_CONSUMER_KEY",
      consumerSecret: "PASTE_CONSUMER_SECRET",
      version: "wc/v3"
    });

    // List products
    api.get("products", {
      per_page: 18, // 18 products per page
    })
      .then((response) => {
        // Successful request
        this.setState({
          products: response.data
        });
      })
      .catch((error) => {
        // Invalid request, for 4xx and 5xx statuses
      })
      .finally(() => {
        // Always executed.
      });
  }

  render() {
    return (
      <div>
        <h2>Products</h2>
        <ul>
        {this.state.products.map(product => (
          <li key={product.id}>{product.name} - ${product.regular_price}</li>
        ))}
        </ul>
      </div>
    );
  }
}

const element = <ProductsComponent></ProductsComponent>

ReactDOM.render(element, document.getElementById("root"));

Here, I am printing the list of product names and product’s price. The user can print other data as well. If you want to see all data in the console, log the response.data in the success method. Just like the above example, you can send other HTTP requests from your React application.

Conclusion

In this tutorial, we study about calling the WooCommerce REST API using PHP and JavaScript. We went through the few API endpoints of WooCommerce. The user can play with the other endpoint following the documentation and sending required HTTP requests.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *