Ruby API Tutorials

How To Use The AliExpress API With Ruby

AliExpress is one of the biggest online retailers in the world. As such, they have enormous amounts of data, ready to be used by applications you can develop yourself. They naturally provide an API so that developers can integrate into their platform. Among other things, you can search for products and get details about them, including shipping information to different countries.

In this article, we’d like to give you an introduction to their API, and build a simple “AliExpress Explorer” app, using Ruby.

Try the API

On RapidAPI you’ll find the AliExpress API ready to use. To play with it, you’ll need to sign up and subscribe to it. After you’ve signed up or logged in, click the “Subscribe to Test” button. Lastly, you can pick the basic plan.

You’re then ready to test the endpoints, which you can find on the left. This API provides five endpoints: search, categories, product listing per category, search, product details, and shipping details. You could start with the search endpoint, and search for something you’d be interested in buying. Click the endpoint, and in the middle section find the parameters at the bottom. Fill the query parameter and click the “Test Endpoint” button above. On the right, you should see the results. Each entry should contain some information (price, a thumbnail URL, etc), and a productId.

You can use this productId to get more details about the product using the /products/{product_id} endpoint. Try it out. You should notice a huge amount of details for the product on the right column,

Build an App with Ruby

Using this API and what you should’ve quickly seen from the results, we’re going to build a simple app that allows you (or your users) to navigate the API easily. This should serve as a good starting point for using this API for other things.

Step 1: Requirements

You’re going to need Ruby. You probably already have it installed on your machine, depending on your operating system. Otherwise, refer to Ruby’s official installation instructions for your specific system. We’re also going to be using Sinatra as our web framework, along with Bootstrap for layout. You can make sure Ruby is installed in your machine by running ruby -v on your terminal. You should see an output like this:

Step 2: The Foundation

Let’s start by creating a new directory for our project. Call it aliexpress, or whatever you like. In this directory, run bundle init to generate a base Gemfile. This file is used to manage our dependencies, so make it look like this:

source 'https://rubygems.org'

gem 'excon'
gem 'json'
gem 'sinatra'
gem 'sinatra-contrib'

Run bundle install to install all dependencies. Then, create a new file called app.rb. This is where we’re mainly going to build our app. Add this to the file:

require 'bundler/setup'
Bundler.require(:default)

require 'sinatra/reloader' if development?

get '/' do
  erb :index, layout: :default
end

This file requires bundler, which in turn requires the dependencies we set up in our Gemfile. Then, we require the Sinatra auto reloader, so that we don’t have to restart our server every time we make a file change (good for development). Finally, we define an index method that renders a template. Let’s create this template now. We’ll need two files for this: one is the template itself (index), and the other is the layout (default). The reason we use a layout is that it allows us to create a single file where we can import our styles and set our default structure for each page, and then use it to wrap all our endpoints, saving us time and avoiding duplicate code. Create a new folder called views and add a file called default.erb to it:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

  <title>AliExpress</title>
</head>
<body>
  <%= yield %>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

This sets up a basic layout, adds Bootstrap (including the Bootstrap Javascript library and jQuery), and Font Awesome for nice icons. In the body, we call yield which will render our templates. Now, create a new file called index.erb in the same views folder, and add this:

<h1>index.erb</h1>

You should now be able to run ruby app.rb in your terminal and go to localhost:4567 on your browser. You should be greeted by “index.erb”!

Step 3: Show Categories

We’re going to start with showing categories. For this, you’ll need to add some methods to your app.rb file:

# ...

RAPIDAPI_KEY = 'YOUR_API_KEY'

def api_request(path)
  response = Excon
    .get(
      "https://ali-express1.p.rapidapi.com/#{path}",
      headers: {
        'x-rapidapi-key' => RAPIDAPI_KEY
      }
    )

  JSON.parse(response.body)
end

def categories
  api_request('categories')
end

get '/' do
  @categories = categories

  erb :index, layout: :default
end

You should make sure you grab your API Key from RapidAPI and replace it in the RAPIDAPI_KEY variable. Next, we define a generic method to make API requests (to avoid repeating code), and a categories method that calls the endpoint with the same name. In the get '/' block, we populate the @categories instance variable with the categories, and then we render our template. Let’s modify the template to look like this:

<div class="container">
  <h2>Categories</h2>

  <div class="row">
    <% @categories['categories'].each_slice(@categories['categories'].count.fdiv(3).ceil) do |categories| %>
      <div class="col-lg-4">
        <ul>
          <% categories.each do |category| %>
            <li>
              <a href="/category/<%= category['id'] %>"><%= category['name'] %></a>
            </li>
          <% end %>
        </ul>
      </div>
    <% end %>
  </div>
</div>

Using some math, we split the categories into three columns (with the help of each_slice). Now, if you refresh your app, it should look something like this:

You’ll also notice we made a link for each category, which points to /categories/{id}. Let’s implement that now.

Step 4: Category Products

Using the same api_request method, we can implement the new endpoint like this:

def products_by_category(id)
  api_request("productsByCategory/#{id}")
end

get '/category/:id' do
  @products = products_by_category(params[:id])

  erb :products, layout: :default
end

With this very simple implementation, we can fetch products for each category the user clicks, and then render them. Now, create a new file in views called products.erb and add this to it:

<div class="container">
  <h2>Products</h2>

  <div class="card-columns">
    <% @products['data']['items'].each do |product| %>
      <div class="card">
        <img src="<%= product['productElements']['image']['imgUrl'] %>" width="100%">

        <div class="card-body">
          <a href="/product/<%= product['productId'] %>">
            <h5><%= product['productElements']['title']['title'] %></h5>
          </a>

          <p>
            <%= product['productElements']['price']['sell_price']['formatedAmount'] %>
          </p>
        </div>
      </div>
    <% end %>
  </div>
</div>

Using Bootstrap’s card columns, we can yield something like this:

Notice how we defined a link for each product? Let’s implement that now.

Step 5: Product Details & Shipping Information

Let’s make a product detail page that also shows the different shipping options available. There are two endpoints for this in the API. Let’s use them and render the product details:

def product(id)
  api_request("product/#{id}")
end

def shipping(id, destination = 'US')
  api_request("shipping/#{id}?destination_country=#{destination}")
end

get '/product/:id' do
  @product = product(params[:id])
  @shipping = shipping(params[:id])

  erb :product, layout: :default
end

Not much difference compared to the previous step, although note we’re defaulting the destination country for shipping calculation to the US. You might want to make this customizable somehow for your users. Now, for the template, we’re going to render a lot of stuff (and not everything, if you check the API response):

<div class="container">
  <h3><%= @product['titleModule']['subject'] %></h3>

  <div class="row">
    <div class="col-lg-5">
      <div class="card mb-3">
        <div class="card-body">
          <h5>Rating</h5>

          <% @product['titleModule']['feedbackRating']['averageStar'].to_f.ceil.times do %>
            <i class="fa fa-star"></i>
          <% end %>

          <%= @product['titleModule']['feedbackRating']['averageStar'] %> avg rating
        </div>
      </div>

      <div class="card mb-3">
        <div class="card-body">
          <h5>Shipping Options</h5>

          <ul class="list-unstyled">
            <% @shipping['body']['freightResult'].each do |shipping| %>
              <li>
                <strong><%= shipping['freightAmount']['formatedAmount'] %></strong> via <%= shipping['company'] %> (est. delivery on <%= shipping['deliveryDateFormat'] || 'unknown' %>)
              </li>
            <% end %>
          </ul>
        </div>
      </div>

      <div class="card mb-3">
        <div class="card-body">
          <h5>Specs</h5>

          <dl>
            <% @product['specsModule']['props'].each do |prop| %>
              <dt><%= prop['attrName'] %></dt>
              <dd><%= prop['attrValue'] %></dd>
            <% end %>
          </dl>
        </div>
      </div>
    </div>

    <div class="col-lg-7">
      <div class="card">
        <div id="carousel" class="carousel slide" data-ride="carousel">
          <ol class="carousel-indicators">
            <% @product['imageModule']['imagePathList'].count.times do |idx| %>
              <li data-target="#carousel" data-slide-to="<%= idx %>" class="active"></li>
            <% end %>
          </ol>

          <div class="carousel-inner">
            <% @product['imageModule']['imagePathList'].each_with_index do |image, idx| %>
              <div class="carousel-item <%= idx == 0 ? 'active' : '' %>">
                <img src="<%= image %>" class="d-block w-100">
              </div>
            <% end %>
          </div>

          <a class="carousel-control-prev" href="#carousel" data-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          </a>

          <a class="carousel-control-next" href="#carousel" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
          </a>
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-lg-12">
      <iframe src="<%= @product['descriptionModule']['descriptionUrl'] %>" height="400" width="100%" frameborder="0"></iframe>
    </div>
  </div>
</div>

Much of this is Bootstrap code. We’re rendering the title, a carousel with pictures, the specs and description (which is just an iframe to a URL), and the shipping options. Take your time to look at the code and see where we get the data from. Now, if you test your app, you should be able to see something like this:

You can click on the arrows to navigate the images, and scroll down to see the seller’s description page.

Step 6: Add Search

The last thing to add is search. There’s not much different to the previous steps: we’ll just add an extra method and a form to our index page:

def search(query, destination = 'US')
  api_request("search?query=#{URI.encode_www_form(query)}&country=#{destination}")
end

get '/search' do
  @results = search(params[:query])

  erb :search, layout: :default
end

Also, modify index.erb to add a search form:

<h2>Search</h2>

<form action="/search" method="get">
  <div class="form-row">
    <div class="col">
      <input type="text" class="form-control" placeholder="Search for a product" name="query">
    </div>

    <div class="col">
      <button class="btn btn-primary" type="submit">Search</button>
    </div>
  </div>
</form>

Lastly, we need to create a new file in views called search.erb:

<div class="container">
  <h2>Search results for "<%= params[:query] %>"</h2>

  <div class="card-columns">
    <% @results.each do |product| %>
      <div class="card">
        <img src="<%= product['productElements']['image']['imgUrl'] %>" width="100%">

        <div class="card-body">
          <a href="/product/<%= product['productId'] %>">
            <h5><%= product['productElements']['title']['title'] %></h5>
          </a>

          <p>
            <%= product['productElements']['price']['sell_price']['formatedAmount'] %>
          </p>
        </div>
      </div>
    <% end %>
  </div>
</div>

This is very similar to the products one. We’ll leave it as an exercise to the reader to optimize this! Now, go to the homepage and search for something, you should get a list of results which you can click through to get more details about each product:

Conclusion

We hope this article gave you a good introduction to the AliExpress API and how to get the most of it using Ruby. We recommend adding pagination to the search endpoint for practice, and so you can get a much better feel for the API. Look at the from and limit parameters in that endpoint.

FAQ

Does AliExpress have an API?

Yes. It provides deep details on each product, including different product variations, prices, offers, specifications, images and much more.

How do you get the AliExpress API?

One way to access it is via RapidAPI. You can find an implementation of the API and how to use it here in this article.

How to get the product description from AliExpress API?

You can find this in this article, on Step 5. Notice how we render an iframe with the product description that the seller sets up for each product.

3.5/5 - (2 votes)
Share
Published by

Recent Posts

Power Up Your Enterprise Hub: New March Release Boosts Admin Capabilities and Streamlines Integrations

We're thrilled to announce the latest update to the Rapid Enterprise API Hub (version 2024.3)!…

2 weeks ago

Unveiling User Intent: How Search Term Insights Can Empower Your Enterprise API Hub

Are you curious about what your API consumers are searching for? Is your Hub effectively…

2 weeks ago

Rapid Enterprise API Hub Levels Up Custom Branding, Monetization, and Management in February Release

The RapidAPI team is excited to announce the February 2024 update (version 2024.2) for the…

4 weeks ago

Supercharge Your Enterprise Hub with January’s Release: Search Insights, Login Flexibility, and More!

This January's release brings exciting features and improvements designed to empower you and your developers.…

3 months ago

Enhanced Functionality and Improved User Experience with the Rapid API Enterprise Hub November 2023 Release

Rapid API is committed to providing its users with the best possible experience, and the…

5 months ago

The Power of Supporting Multiple API Gateways in an API Marketplace Platform

In today's fast-paced digital world, APIs (Application Programming Interfaces) have become the backbone of modern…

6 months ago