How to Proxy the BigCommerce API Using Serverless Functions and Amazon API Gateway
The BigCommerce Stencil theme framework is powerful and offers a lot of customization options, but sometimes we want to get information from the store that isn’t available in the default Stencil object. For example, let’s say you want to get all of a product’s variants to populate a bulk order form.
After reading over the BigCommerce developer documentation, it looks like the Catalog API returns everything we need. In one API call, you can get all of a product’s details, including variant information.
However, since it requires authentication, this API is restricted to server side applications. What if we want to develop a front end script that uses information from this API? It’s important that we never expose API credentials on the front end, so we need a safe way to make the API request and pass the information to the storefront. To solve this problem, we need to build middleware.
Why Use Serverless Functions?
We want to build middleware that proxies an API request and returns the response to our front end. Instead of going through the trouble of setting up a production environment for this single task, we can take advantage of serverless functions. This kind of service is available from multiple providers, including AWS Lambda, Google Cloud Functions, and Azure Functions.
The advantage of using these services is that they scale automatically, and enable the development of back-end functionality without worrying about managing your own servers. In this post, we’ll cover building a serverless function on AWS to return product variant data to our BigCommerce storefront.
Getting Started on AWS
Set up an account on AWS and navigate to the Management Console. From here, navigate to Services and select Lambda. Once you’re in the Lambda section, you’ll want to create a function.
For our example function, we’ll select the Start from Scratch option and use the nodeJS 8.10 runtime. To keep it simple, name your function something like get-variants.
Once you’ve created the function, you’ll be directed to a page that has a built in code editor and the option to select a trigger for the function. Let’s get our code set up first.
Writing the Function
We need to make a request to the API, so we’ll write a simple HTTPS request in Node. I’ve included the code I used for the bulk form article below:
const https = require('https');exports.handler = async (event) => {
let product_id = event["queryStringParameters"]["product_id"];
async function getVariants(id) {
const options = {
host: 'api.bigcommerce.com',
path: `/stores/my-store-hash/v3/catalog/products/${id}/variants?include_fields=calculated_price,inventory_level,sku,option_values,image_url`,
headers: {
accept: 'application/json',
'X-Auth-Client': process.env.CLIENT_ID,
'X-Auth-Token': process.env.TOKEN
}
}
return new Promise((resolve, reject) => {
const request = https.request(options, (response) => {
console.log('requesting')
let body = '';
response.on('data', (rawData) => {
body += rawData;
})
response.on('end', () => {
resolve(JSON.parse(body));
})
});
request.on('error', (err) => {
reject(err)
});
request.end();
})
}
const response = {
"statusCode": 200,
"body": JSON.stringify(await getVariants(product_id)),
"headers": {
"Access-Control-Allow-Origin": "*"
}
}return response;
};
Our function takes a product ID as a query param and passes it to the path of our API request. The response, including the results of the API request, will be passed to our store’s front end. This particular request returns the calculated_price, inventory_level, SKU, option_values, image_url, and variant id of each variant, but you can modify the included fields or choose to omit the param altogether to get the default values returned by this endpoint.
There are a few things that need to be configured to get this code working for your own store. First, you need to substitute my-store-hash in the path with your own store hash value. You’ll also need to add 2 environment variables for the CLIENT_ID and TOKEN. If you scroll below the code editor, you’ll see the area to add environment variables.
To get your client id, token, and store hash, you can generate API credentials in your BigCommerce store by navigating to Advanced Settings > API Accounts. Note that if you are not the owner account on a store, you will need to be made the owner or have the owner generate these for you.
You may also want to modify the Access-Control-Allow-Origin header to match your specific store’s domain, rather than allowing anyone to make a request to your endpoint.
Setting Up the Function Trigger
Now that we have our code ready, we need to set up a trigger to run the code. At the top of the page, you should see a section to add triggers. Select API Gateway and choose to create a new API in the configuration section. We’ll keep the security set to Open because this API needs to be accessible to our front end requests.
Once you’ve saved the API Gateway as a trigger, you should see a link to navigate to the API Gateway dashboard when selected.
Navigate back to the console to manage the API Gateway, where you can remove the default ANY method and add GET as a method in the Actions menu. Once you have GET added as a method, select it in the menu and click on Method Request. In here we’ll add product_id as a query parameter.
Next, we’ll navigate back a step by clicking Method Execution, then selecting Integration Request. This is where we can attach our Lambda function to the method. For Integration Type, select Lambda Function. Next, check the box by Use Lambda Proxy integration. This will allow us to access the query string params passed in the request to our API endpoint. Finally, in the Lambda Function field, input the name of the function i.e. get-variants.
Calling the Function
You can test your new Lambda function directly within the API gateway console. After you click test, you can pass in a query param including a product ID from your store and see the response your front end script would receive. When this is successful, you can begin calling your API endpoint from your front end code on your BigCommerce store!
Once you have access to the response data on the front end, you can build all kinds of interesting functionality around it. You could show variant images or inventory levels on category pages, or create a product recommendation app. For a full end-to-end example, check out my blog post on building a bulk order form to add multiple variants to the cart on the product page.