How to use Amazon Product/Review APIs in JavaScript

Why use Amazon APIs in JavaScript?

Amazon has quickly become one of the most trusted online retail stores. Not only does Amazon have a great selection of products, but it’s also a great source of customer reviews. Add to this a great return policy, an easy to use website and mobile app, and Amazon’s reputation of reliability, and you can start to see why so many people choose Amazon for much of their shopping needs.

Now, JavaScript developers can also tap into the huge treasury of Amazon’s product listings and reviews. Using APIs, software developers can now create JavaScript apps that take advantage of this immense amount of data to build or enrich their own apps in a variety of ways. For example, businesses which sell products can embed Amazon reviews of their own products directly on their own websites, using JavaScript APIs.

Example: Amazon Search JavaScript App

In this tutorial, we’ll build a very simple but powerful search app in pure JavaScript, which will use Amazon APIs. Users will be able to search for products by keywords, and load reviews for a product that looks interesting to them. This will give us a high-level look at using Amazon’s APIs in JavaScript. At the end of this blog post, our JavaScript Amazon Product Search app will look like this:

Step 1: Find some Amazon Product/Reviews APIs

When searching the web for JavaScript engines, the results led me to RapidAPI.com. If you don’t already have a RapidAPI account, make sure to sign up for a free account, before moving forward. As a bonus, you’ll get instant access to many more APIs.

After checking out the Amazon APIs available on RapidAPI, I settled on the Amazon Product/Reviews/Keywords API. It has just what we’re looking for: the ability to list products, and list the reviews for a given product.

This is a Freemium API, which means it has a free tier for basic tests, with a hard limit. In this case, we can only make about 25 requests. But that should be plenty for us, since our app will only make 1 request per button-click.

So before we continue, make sure to subscribe to this API. RapidAPI may ask for payment information, but don’t worry, RapidAPI won’t charge you anything since this API doesn’t charge for any API calls. Plus, you’ll more easily be able to upgrade to a paid tier of any API that you find useful.

Step 2: Try the API out on RapidAPI

Now that we’ve subscribed, let’s try out the APIs directly in RapidAPI. There are only two API Endpoints we’re interested in: Product Search and Product Reviews.

Tip: Not sure what an API Endpoint is? Check out What is an API Endpoint?

Notice that each endpoint only has one required parameter. For Product Search this is keyword. This must be URI-encoded when passed to the API, since it will be passed as a query parameter.

And for Product Reviews, this is asin. In Amazon’s API terminology, an ASIN is basically a globally unique identifier for a product.

So let’s test out the Product Search from RapidAPI and take a look at what kind of data we get back:

Great, we got an array back that has all the fields we need. We have “title”, “thumbnail”, “url”, “price.current_price”, and “reviews.rating”. We also have the “asin” of this product, which will let us call the Product Reviews API for each product we find here.

When we run the Product Reviews API inside RapidAPI, we see similar data:

Great, plenty of data. We’ll pluck out “title”, “review”, and “rating” for our app’s purposes. But it’s good to know what other data this API also gives us.

Step 3: Prepare our HTML file

Now we can actually start building our app!

For a simple JavaScript app, all we need is an HTML file with a <script> tag. So open your favorite IDE (I heartily recommend VS Code) and paste the following into a file named index.html:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Amazon JavaScript API Demo</title>
  <style>

    /* CSS will go here */
  </style>
</head>

<body>

  <h2>Product Search</h2>
  <input autofocus id="searchTerm" value="laptop">
  <button >

We can already see the basic structure of our app. There’s a header, an input field which the user can type their search term into, a button that lets them search, and a products section that starts off empty.

Important: There’s an empty variable here called RAPID_API_KEY. Make sure to fill this string in with the RapidAPI key that you see in the API Endpoint page! This is necessary for our JavaScript Amazon API app to work!

Step 4: Fill in the JavaScript logic

Now that we have the visual structure laid out, let’s fill in the JavaScript logic. In particular, our “Search” button calls the search() function when clicked, but that function doesn’t exist! So let’s define it.

Add the following code to the end of the <script> tag:

async function search() {
  const productsContainer = document.getElementById('products');
  productsContainer.innerHTML = 'Loading...';

  const { products } = await searchProducts(document.getElementById('searchTerm').value);
  productsContainer.innerHTML = products.map(product => `
    <li class="product grid cols">
      <span class="thumbnail"><img src="${product.thumbnail}"></span>
      <div class="metadata grid medium">
        <a class="title" href="${product.url}">${product.title}</a>
        <span class="rating"><b>Overall Rating:</b> ${product.reviews.rating} / 5</span>
        <span class="price"><b>Price:</b> $${product.price.current_price}</span>
        <div class="reviews">
          <button class="subtle" >

This code is simple to understand when we break it down into parts:

  1. On the first line, we get a reference to the container element that will hold product reviews after we’re done loading.
  2. The next line fills this container with the string “Loading…” so our users know that they’re waiting on something.
  3. Then, we grab the value of the input field, pass it to searchProducts(), and wait for the Promise object to resolve. This function calls the Amazon API, so it returns a Promise, because we don’t want to block the UI while it loads.
  4. After it loads, we set the product container’s HTML to show each product’s thumbnail, price, rating, and title as a link.
  5. We also created a container that will hold the reviews when the “Show Reviews” button is clicked.
  6. The click handler for the “Show Reviews” button hard-codes this product’s ASIN, so that later, we can tell the Amazon API which product to load reviews for.

But this references two functions that don’t exist! We’ll worry about searchProducts in a bit, since that involves calling the API. For now, let’s focus on the showReviews(...) function.

Add the following code to the bottom of your <script> tag:

async function showReviews(reviewsContainer, asin) {
  reviewsContainer.innerHTML = 'Loading...';

  const { reviews } = await getReviews(asin);
  reviewsContainer.innerHTML = `
    <h3>Reviews</h3>
    <ul class="grid">
    ${reviews.map(review => `
      <li class="grid small table">
        <span><b>Rating:</b> ${review.rating} / 5</span>
        <span><b>Title:</b> ${review.title}</span>
        <span><b>Review:</b>
          <span>
            ${review.review.slice(0, 100)}...
            <a href='#' style="color:inherit" >

This follows almost the same structure as the last function:

  1. We show “Loading…” in the Reviews section.
  2. We wait for getReviews(...) to finish its API call.
  3. When the data is loaded, we show all the reviews, mapping each one’s rating, title, and review into HTML.
  4. We also have a simple “Read More” link, which has a click handler that unhides the element containing the full-review, and replaces the parent container with it.

That’s most of the logic for our app! Simple, right? There’s only one thing missing: API calls.

Step 5: Call Amazon APIs from JavaScript

Let’s go back to our endpoint pages again for Product Search and Product Reviews. On the right of each page, you’ll see the Code Snippets tab. Choose the language dropdown, hover over the JavaScript sub-menu, and select fetch.

We’re using fetch() in this example because async functions are extremely convenient. They work naturally with API calls, because they let you write code as if it were linear, but in reality any amount of time can pass between the request and response.

Tip: Not sure exactly what an API Request is? Check out What is an API Request?

You’ll see something like in the image above. But notice that this is using the regular Promise API, with .then and .catch method calls. It’s generally easier to use async/await syntax, so for your convenience, I’ve transformed both functions for us:

Paste the following two functions into the bottom of your <script> tag:

async function searchProducts(term) {
  const response = await fetch("https://amazon-product-reviews-keywords.p.rapidapi.com/product/search?country=US&keyword=" + term, {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "amazon-product-reviews-keywords.p.rapidapi.com",
      "x-rapidapi-key": RAPID_API_KEY
    }
  });
  const body = await response.json();
  console.log(body);
  return body;
}

async function getReviews(asin) {
  const response = await fetch("https://amazon-product-reviews-keywords.p.rapidapi.com/product/reviews?country=US&asin=" + asin, {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "amazon-product-reviews-keywords.p.rapidapi.com",
      "x-rapidapi-key": RAPID_API_KEY
    }
  });
  const body = await response.json();
  console.log(body);
  return body;
}

These are simply adding the parameters to the query string, and calling the Amazon API. After transforming the body into JSON so we can read it in JavaScript, we return the JSON directly from each function. Easy!

Tip: For a more in-depth look at using APIs from JavaScript, check out How To Use an API with JavaScript (The Complete Beginner’s Guide).

Step 6: Add some CSS styling to our JavaScript app

Our app works right now! But it’s not that pretty. So let’s take a little time to clean it up. Thanks to modern CSS, and especially CSS Grid, it only takes about 50 lines of CSS to make our Amazon Product/Reviews Search app look respectable.

So let’s add the following CSS to the <style> tag near the top of index.html:

body {
  font-family: sans-serif;
  background: #f7f7f7;
  padding: 3em;
  width: 50em;
}

input,
button {
  padding: 0.5em 0.75em;
  margin-right: 1em;
  border-radius: 4px;
  outline: none;
  border: 1px solid transparent;
  font: inherit;
}
input         { border-color: #888; }
input:focus   { border-color: #17f; }
button        { background: #17f; color: #fff; }
button:active { background: #15d; }
button.subtle { background: #fff; border-color: currentColor; color: #17f; }
button.subtle:active { background: #eee; }

.grid {
  display: grid;
  gap: 1em;
  align-content: start;
  justify-content: start;
}

.grid.cols   { grid-auto-flow: column; }
.grid.small  { gap: 0.25em; }
.grid.medium { gap: 0.5em; }

.product {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0px 1px 6px 2px #0002;
  padding: 1em;
}

ul { padding-left: 0; }

.thumbnail {
  width: 150px;
  text-align: center;
}

.thumbnail img {
  max-width: 100px;
  max-height: 100px;
}

Step 7: Try it out!

Load the file in your favorite modern browser, and try it out! It should look something like this:

Give yourself a pat on the back. With very few lines of JavaScript code, you made your very own Amazon search app!

Conclusion

Amazon Product and Review APIs give you instant access to an immense amount of useful data. By applying a little imagination and thought, there’s no telling what kinds of things you can do with this data in JavaScript.

FAQ

How do I pull data from Amazon?

There are several APIs from Amazon, and one of the easiest ways to use Amazon's API is through RapidAPI. In this article, we simply passed a search term to our Amazon API, and it returned product information back to us, in a detailed and useful JSON format. We also passed a product 'asin' to another API Endpoint, and received review data in a similar JSON format.

How does this Amazon API compare with Amazon AWS APIs?

Amazon has many APIs under the title of Amazon Web Services, or AWS. The AWS APIs are unrelated to Amazon products/reviews, and are meant to help developers build websites and apps. Using Amazon Product/Review APIs lets you get information about products and their reviews from Amazon's web store.

5 / 5 ( 1 vote )
Steven

With over a decade of professional front-end experience, Steven uses his accumulated knowledge and experience to write instructive technical articles about the latest technologies such as JavaScript, TypeScript, React.js, and many APIs.

Share
Published by

Recent Posts

API Testing Tutorial: API Testing with RapidAPI

What is API Testing? API testing is a type of software testing that involves testing application programming interfaces (APIs) directly…

6 days ago

Test APIs From Development to Deployment with RapidAPI Testing

We are excited to introduce RapidAPI Testing — a functional API testing solution for creating…

7 days ago

Build a Influencer Search App with Ruby on Rails

Internet search has gone way beyond the traditional web search. Thanks to other mediums of…

4 weeks ago

React API Authentication & Authorization

Introduction Security on the internet comes under scrutiny the more our personal lives and business…

4 weeks ago

How to use WordPress with React (WordPress React API Tutorial)

WordPress WordPress claims to be, "the world’s most popular website builder" based on the statistic…

1 month ago

How to use an E-mail API with JavaScript

Introduction This tutorial will show you how to use JavaScript to call an API to…

1 month ago