How to use the Amazon Product API in Ruby

RapidAPI Team
The Era of APIs
Published in
8 min readNov 19, 2019

Amazon is by far the biggest online retailer in the world. Founded in 1994, it’s been growing from a small garage startup to a multinational sales and technology leader for 25 years.

As such, the amount of data about the products they sell on their marketplaces is enormous, and this is not something they chose not to share. The sales giant provides APIs with product information that allows developers to build services around this.

Read the full article on RapidAPI

What is the Amazon Product API

The Amazon Product API is a service that allows you to access Amazon’s vast data on the products listed on their marketplaces. In general, it provides most of the same functionality you’d find on their website, via an Application Programming Interface. This means:

  • Product Search: allows finding products using keywords, just like the Amazon search bar at the top of their website,
  • Product Details: get details about products, for example, the price and brand,
  • Customer Reviews: ratings about a product,
  • among others.

This allows developers to build endless services around the Amazon API, and RapidAPI has a number of APIs available to interface with the giant’s service seamlessly.

Connect to the Amazon Price API

What we will build

In this article, we’ll show you how to use the Amazon Product API. We’ll build a service that allows searching for a product using keywords, show its current price and also show a price report.

The flow will be as follows:

  1. The user loads our web service, sees a search bar
  2. The user enters some keywords (for example, “MacBook Pro”)
  3. Our web service queries the Amazon Product API via RapidAPI, gets a list of results
  4. We display these results to the user in a table, showing a picture of the product, title, price, etc.

Requirements

For this project you’ll need:

To install Ruby, your best bet is to follow their official installation guide. Also, you can see a quick review of some of the different frameworks you can choose to build your applications here. We’re choosing Sinatra this time, due to its simplicity and quick setup. In any case, what we’ll write here can easily be ported to any Ruby framework in no time.

Related: How to use an API with Ruby

To install Sinatra, just run gem install sinatra in your terminal. That's it!

You will also need a RapidAPI account. Simply head on to rapidapi.com and set one up. RapidAPI makes working with different APIs a lot easier, and most of them have a free tier for you to try.

Setup our project

Since we’re using Sinatra, there isn’t much setup to be carried out. Sinatra prides itself on being simple yet powerful. To get started, create a new folder called amazon-api:

mkdir amazon-api

We’ll also need to add a Gemfile to setup our dependencies. Go ahead and add this to the file:

# Gemfile source "https://rubygems.org" gem "sinatra" gem "excon"

We will use excon our network library to reach RapidAPI and the Amazon Product API. More on that later, for now, go ahead and run bundle install to get everything installed.

Create the app and the first page

First, let’s set up our app and the first page, which will contain our search form. For the sake of simplicity, we’ll keep our whole service in a single file, but Sinatra supports splitting your app into multiple files for more maintainability. For now, just create a file called app.rb and put this in:

# app.rb require 'sinatra' get '/' do erb :index, layout: :default end

Let’s go over this real quick. We first require Sinatra, which will turn this file into a Sinatra service (using some convenience methods like get). We then define the root path: any GET request to the root path will call the block passed, which in this case renders a template using ERB. Embedded Ruby is a simple way of embedding ruby code into HTML, in this case, to create dynamic websites. Here, Sinatra will look for the file views/index.erb and it will render that file into the passed layout (in views/default.erb). Let's create those now:

<!-- views/default.erb -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Amazon Product API</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<main>
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Amazon Product API</h1>
<form action="/search" method="get" accept-charset="utf-8">
<input type="text" value="" name="query" id="query" placeholder="Search for a product" class="form-control">
</form>
</div>
</section>
<!-- Render our websites here -->
<%= yield %>
</main>
</body>
</html>

This will be our “layout”, that is, a generic container for our other sections of the service. This way, the search form will always be available to our users right at the top, and our sections will be rendered wherever we call yield inside of this layout. We're also importing Bootstrap for easier styling.

Let’s now define our index page, which will just contain a short introduction:

<!-- views/index.erb -->
<section>
<p class="text-center">Use this service to search for a product in Amazon.</p>
</section>

Nothing fancy here, the magic will come later.

Setup our API provider

Before moving on to the next steps, we need to subscribe to one of RapidAPI’s Amazon Product APIs. There are quite a few, and for this article, we decided to go with “ Amazon Price “. It provides endpoints to search for products in different marketplaces, get price reports on products, among others. To use it, you’ll need to subscribe to it. Don’t worry, it has a free usage tier, so there’s no need to commit to it in advance. To subscribe, go to the Pricing page and press the “Subscribe” button on their Basic plan:

You’re now ready to continue. We can now query the API and get search results.

Finding products

If you look at the form we defined in the previous step, you’ll notice a single text field with the name query. When the user presses enter, this query will be sent to our search endpoint, where we'll search for the product using the Amazon API and render the results. Let's define that route now. Add this to your app.rb file:

# app.rb
require 'sinatra'
require 'excon'
require 'json'
# ...get '/search' do
query = URI.encode(params['query'])
url = "https://amazon-price1.p.rapidapi.com/search?keywords=#{query}&marketplace=US"
response = Excon.get(
url,
headers: {
'X-RapidAPI-Host' => URI.parse(url).host,
'X-RapidAPI-Key' => 'YOUR API KEY'
}
)
results = JSON.parse(response.body)
erb :results, layout: :default, locals: { results: results }
end

At the top, we’re requiring both Excon and JSON gems. These will allow us to query and process the Amazon API. Then, below, we’re adding a new method handler: GET on the /search path (remember the form?). We grab the query parameter, which we then encode to be able to pass along to the Amazon API. From here we construct the URL we'll get the results from. You can get this from your RapidAPI Dashboard, along with your API Key:

Using Excon, we make a get request to our endpoint, passing along some headers. X-RapidAPI-Host is needed for RapidAPI to be able to identify the request correctly, and X-RapidAPI-Key is needed to be able to authenticate the request, so they know it's us. The results come in JSON format, which we then parse.

Displaying the results

At the end of the method in the previous step, we render a view called results.erb. We pass the results as a locals so our template can access the array of results. Let's go ahead and create that view real quick:

<!-- views/results.rb -->
<section>
<% results.each do |result| %>
<div class="media">
<img src="<%= result['imageUrl'] %>" class="mr-3">
<div class="media-body">
<h5 class="mt-0">
<a href="<%= result['detailPageURL'] %>"><%= result['title'] %></a>
</h5>
Price: <%= result['price'] %> <br>
List Price: <%= result['listPrice'] %> <br>
Rating: <%= result['rating'] %>/5 <br>
Prime: <%= result['isPrimeEligible'] ? 'Yes' : 'No' %>
</div>
</div>
<hr>
<% end %>
</section>

We loop over the results array and use a Bootstrap media component to render the picture of the product, its name and link, plus some more information about the current price, list price, rating and whether it’s available via Amazon Prime. You can take a look at all the information you get in the response by testing the endpoint right in the RapidAPI Dashboard:

Taking our project for a spin

All that’s left to do it to run ruby app.rb in your terminal, and your application should be up and running. You should see something similar to this output in your shell:

[2019-11-16 23:27:48] INFO  WEBrick 1.3.1
[2019-11-16 23:27:48] INFO ruby 2.3.7 (2018-03-28) [universal.x86_64-darwin18]
== Sinatra (v2.0.7) has taken the stage on 4567 for development with backup from WEBrick
[2019-11-16 23:27:48] INFO WEBrick::HTTPServer#start: pid=83469 port=4567

Open your browser and go to http://localhost:4567. You should be greeted by your project. Here’s a small video of it in action, and of what you should expect:

Connect to the Amazon Price API

Where to go from here

We hope this article gave you an idea of how to start working with the Amazon Product API using Ruby. What you learned here can easily be applied to other Ruby frameworks like Ruby on Rails or Roda. Note that the Amazon Product API provides more than what was discussed here. That means you can extend the service we built a bit further by using the priceReport endpoint to display some more price details, like high and low prices, plus the price of the product in a used state.

Originally published at https://rapidapi.com on November 19, 2019.

--

--