Updated: 25th January 2021
Excited to share finally a JavaScript library to help with your headless store development. Much like the WooCommerce JavaScript Library, this one is designed so authentication is optional.
Where to get it?
You can install the JavaScript Library simply running this command in your terminal.
npm install --save @cocart/cocart-rest-api
If you wish to contribute to the project you can access the GitHub repository.
Example of Use
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM const CoCartAPI = require("@cocart/cocart-rest-api").default; const CoCart = new CoCartAPI({ url: "http://example.com" });
You can decide to use CommonJS (CJS) or ECMAScript Modules (ESM).
Since there is only one API version at this time there is no need to define the version when setting up your API constant. All that is required is the URL of your site.
FYI
This library will NOT support the LEGACY API of CoCart.
If you are authenticating a customer then you need to set the consumerKey (a.k.a Username) and consumerSecret (a.k.a Password).
// import CoCartAPI from "@cocart/cocart-rest-api"; // Supports ESM const CoCartAPI = require("@cocart/cocart-rest-api").default; const CoCart = new CoCartAPI({ url: "http://example.com", consumerKey: "sebtest123", consumerSecret: "happycoding24" });
You can then proceed to use the library to make requests like so.
Get Cart
// Get Cart CoCart.get("get-cart", { thumb: true, // Returns product thumbnail }) .then((response) => { // Successful request console.log("Response Status:", response.status); console.log("Response Headers:", response.headers); console.log("Response Data:", response.data); }) .catch((error) => { // Invalid request, for 4xx and 5xx statuses console.log("Response Status:", error.response.status); console.log("Response Headers:", error.response.headers); console.log("Response Data:", error.response.data); }) .finally(() => { // Always executed. });
Add item to cart
// Add item to cart CoCart.post("add-item", { product_id: "32", quantity: 1 }) .then((response) => { // Successful request console.log("Response Status:", response.status); console.log("Response Headers:", response.headers); console.log("Response Data:", response.data); }) .catch((error) => { // Invalid request, for 4xx and 5xx statuses console.log("Response Status:", error.response.status); console.log("Response Headers:", error.response.headers); console.log("Response Data:", error.response.data); }) .finally(() => { // Always executed. });
You can view other examples provided in the documentation. Simply click on Node.js in the top right corner to see the command.