Separate your product catalog from commerce.

Tutorials

Getting started with Commerce Layer JavaScript SDK.

April 14, 2022 Bolaji Ayodeji

Commerce Layer provides a JavaScript SDK that makes it quick and easy for developers to interact with our commerce APIs. The SDK simplifies the building of requests and the reading of responses allowing you as a developer to easily build requests to our APIs. With the SDK, responses from our APIs are not returned RAW but denormalized by the SDK, so a related resource is presented as a normal field of the main resource. Generally, with the SDK you get some features like:

  • Simplified request writing and response reading for developers.
  • Automatically generated SDK functions and resources from our public OpenAPI schema. From a developer perspective, the fact that we generate our SDK starting from our OpenAPI schema is a guarantee of consistency. You will find only operations, resources, and fields that are present on the schema of our API in the SDK.
  • Typescript support for defined typing and increased team performance.
  • Unit testing executed without calling the API for each resource/operation which makes the SDK highly reliable.

Without further ado, let’s get started! :)


Prerequisites


Why JavaScript?

Commerce Layer is client-side friendly and we’re big advocates of the Jamstack, the new standard architecture for the web that makes huge use of JavaScript for building better performant, scalable, and secured applications. Also, a large part of our existing client's brands makes use of JavaScript so we’re investing heavily in building tools to support developers building with Commerce Layer. While this is said, we’re also open to building even more tools to support developers working with other technologies who will join us now and in the future.

Getting started

To get started with Commerce Layer JavaScript SDK, you need to install it as a package, get some credentials you need to perform API calls, and generate an access token.

Installation

You can install either the npm package:

npm install @commercelayer/sdk

Or the yarn package:

yarn add @commercelayer/sdk

Upon successful installation, you can import the SDK into your project like so:

import CommerceLayer from '@commercelayer/sdk'

Authentication

All requests to Commerce Layer API must be authenticated with an OAuth2 bearer token. Hence, before starting to use this SDK you need to get a valid access token. To get an access token, you need to execute an authorization flow by using a valid application type as the client. Each application type has its own usage, authentication flow, and permissions. There are three application types: sales channel, integration, and webapp. Each of these applications can be authenticated with different authorization grant flows using the available authorization grant types as described in the table below:

  • The client credentials grant type gives you a "guest" access token to both sales channel and integration applications.
  • The password grant type gives you an access token to sales channel applications in exchange for customer credentials.
  • The authorization code grant type is used by backend applications to exchange an authorization code for an access token.
  • The refresh token grant type is used by clients to exchange a refresh token for an expired access token.

Access tokens generally expire after 2 hours for security reasons (duration can be set for each applications on the Dashboard), so you will need to get a new token upon expiration. Also, you should note that each access token generated based on the application types gets a specific set of permissions. For example, sales channel applications can read resource lists only for SKUs, SKU options, prices, promotions, and bundles. Anything outside this will require another application type. You can read the documentation to learn more about the available roles and permissions or for further information on authentication with Commerce Layer APIs.

For the sake of this tutorial, we will use the Commerce Layer JS Auth library — a JavaScript library that helps you wrap around our authentication API and get the authentication named method for each of the flows mentioned earlier. (client_credentials, password, authorization_code, and refresh_token)

This will enable us to get an access token to use with the SDK. Ideally, you will do the same thing when you’re building your ecommerce project with the SDK. You will get an access token, save it as a cookie while it’s not expired (if expired, the cookie is deleted and the function will request for a new token), as seen in the code below:

import Cookies from "js-cookie";
import { authentication } from "@commercelayer/js-auth";

(async () => {
let token = "";
  const getCookieToken = Cookies.get("clIntegrationToken");
  if (!getCookieToken && CLIENT_ID && CLIENT_SECRET && SLUG) {
    const auth = await authentication("client_credentials", {
      slug: SLUG,
      clientId: CLIENT_ID,
      clientSecret: CLIENT_SECRET
    });
    token = auth.accessToken;
    Cookies.set("clIntegrationToken", token, {
      expires: auth.expires
    });
  } else {
    token = getCookieToken || "";
  }
  return token;
})();

How it works

To show you how the SDK works, we’re going to perform some CRUD (Create, Retrieve, Update, and Delete) operations on the SKU resource. To help you through this tutorial, we’ve created a sandbox with all the code samples for you to follow. It might help as you go through every step of how to use our SDK. To get started, you have to initialize the SDK like so:

const cl = CommerceLayer({
  organization: 'your-organization-slug',
  accessToken: 'your-access-token'
})

When you use the SDK to make any request to any of our API endpoints, the API will respond with an HTTP response code to show the success or failure of the request. You can explore the full list of our API response codes and how to handle them in our documentation. You can also head to the Commerce Layer dashboard to preview the resource (if created or updated).

Create

To create a new SKU, you need to send a POST request to the /api/skus endpoint, passing the resource arguments in the request body as described in the API reference. An SKU needs to be associated with a shipping category that determines the available shipping options for that SKU. Depending on your use case, you might want to create new SKUs via the order management system in the Commerce Layer dashboard, or through our CLI. We used the CLI to get the shipping category ID (which is JNxyxFLOXw) for the shipping category we created before (named Merchandising) and created a new SKU with the SDK like so:

const createSku = async () => {

  const newSku = await cl.skus.create({
    shipping_category: cl.shipping_categories.relationship("JNxyxFLOXw"), // assigning the shipping category relationship
    code: "HOODIEGR0001XLXX",
    name: "Grey Coding Hoodie",
    description: "A very beautiful and cozy unisex hoodie",
    reference: "HOODIEGR0001",
    weight: "500",
    unit_of_weight: "gr"
  });

  console.log(`SKU: ${newSku.id} created succefully`);
  console.log(createSku); // this will return the created resource object
};

Retrieve

To retrieve an SKU, you need to send a GET request to the /api/skus/:id endpoint, passing the ID of the SKU you want to fetch. You can fetch all SKUs in your market with the SDK like so:

const fetchSkus = await cl.skus.list()
Filtering the results

When you request some resources, you can filter the results to return specific data using the filters query parameter. With the SDK fetch a particular SKU with the SKU code like so:

const fetchSku = await cl.skus.list({
  filters: { code_eq: "HOODIEGR0001XLXX" }
});

You can fetch only the SKUs whose code contain a particular string like so:

const fetchSkus = await cl.skus.list({ filters: { name_cont: "Hoodie" } })

You can fetch only the SKUs whose code starts with a particular string like so:

const fetchSkus = await cl.skus.list({ filters: { code_start: "HOODIE" } })

You can fetch only the SKUs whose code ends with a particular string like so:

const fetchSkus = await cl.skus.list({ filters: { code_end: "XLXX" } })

You can fetch only the SKUs created between two specific dates like so:

const fetchSkus = await cl.skus.list({
  filters: { created_at_gt: "2022-01-01", created_at_lt: "2022-04-01" }
});
Sorting the results

When you request some resources, you can sort the results to be returned in a specific manner using the sort query parameter. For example, you can sort the returned SKUs by creation date in ascending or descending order like so:

// Sorts in ascending order (this is the default behavior)
const fetchSkus = await cl.skus.list({ sort: { created_at: "asc" } })

// Sorts in descending order
const fetchSkus = await cl.skus.list({ sort: { created_at: "desc" } })
Including associations

When you make a request for some resources, you can include other related resources as associations using the include query parameter. For example, you can fetch an SKU and include the related prices or stock items like so:

const fetchSkus = await cl.skus.list({ include: [ "prices" ] })

const fetchSkus = await cl.skus.list({ include: [ "stock_items" ] })
Returning specific fields

When you make a request for some resources, you can return only specific fields using the fields query parameter. For example, you can fetch an SKU and return only the name, description, and weight fields and like so:

const fetchSkus = await cl.skus.list({ fields: { skus: [ "name", "description", "weight" ] } })
Pagination

When you fetch a collection of multiple SKUs with skus.list(), the results are grouped into pages. The default behavior is that only 10 items are returned on each page (this applies to other Commerce Layer resources too). You can customize this behavior and return specific pages or increase the items on each page up to 25:

const fetchSkus = await cl.skus.list({ pageNumber: 2, pageSize: 15 })

This will also return the current page, the total number of SKUs in the collection (recordCount), and the total number of pages (pageCount) in the meta object.


There’s so much more you can do when retrieving resources from Commerce Layer. Eventually, when you fetch data from Commerce Layer, you can map through to get specific data you need like the SKU code, associated prices, and more.

Update

You can update an SKU by sending a PATCH request to the api/skus/:id endpoint, passing the resource arguments you want to update in the request body as described in the API reference:

const updateSku = cl.skus.update({
  id: "BdplSqwDLb",
  name: "Grey Programming Hoodie",
  description: "Add a new description here",
  weight: "600"
});

Delete

To delete an SKU, you need to send a DELETE request to the api/skus/:id endpoint, passing the SKU id in the request body as described in the API reference:

const deleteSku = cl.skus.delete("BdplSqwDLb");

Conclusion

We hope you have learned the fundamentals of our commerce APIs and how to use the JavaScript SDK to make requests to any of our API endpoints. You can find all the code examples used in this sandbox. The same CRUD operations we’ve practiced can be performed on other resources (the following example shows how to create a customer):

(async () => {
  const createCustomer = await cl.customers.create({
    email: "testuser@commercelayer.io"
  });

  console.log(`Customer: ${createCustomer.id} created succefully`);
  console.log(createCustomer); // this will return the created resource object
})();

Commerce Layer provides 400+ endpoints and you can explore our API reference to learn more about other core resources you can play around with and use while building your ecommerce project. As we progress and grow our community, we will develop other language-specific SDKs and libraries to enable you to achieve more with Commerce Layer. We believe in the developer-first approach and we’re constantly building for your happiness and success. Feel free to join our global Slack community if you need any help or have suggestions to share.

Our JavaScript SDK is open-sourced on GitHub and we appreciate your contribution, improvement suggestions, or bug reports.