Fetching Products From An API

shopping bag logo

What is an API?

An API stands for Application Programming Interface. It allows two services/software/computer components to communicate in a standard way.

Many popular apps and websites have an API available. Some examples include:

  • Displaying your own social media posts from a social media providers API.
  • YouTube providing API access to use their videos on your site.
  • A travel company can get hotel and flight data from an API service or third party company.

This gives companies a controlled way to provide data they are happy to share. Many API providers will require registration and have a security process to follow when requesting data.

Getting started with Faker

We will be using a third-party API to fetch product data from https://fakerapi.it. Faker is a collection of API's to generate mock data to work with in our project. This is free to use and requires no sign up to use. It includes mock data for testing our application including companies, credit cards, books, users, but we will be using the products data. We often request API data from a URL, the base URL for Faker is:

https://fakerapi.it/api/{version}

Using version v2, we could request different types of data as follows:

https://fakerapi.it/api/v2/books
https://fakerapi.it/api/v2/companies
https://fakerapi.it/api/v2/users

You can copy and paste any of these URL's into the browser and you will see the data returned. There is also parameters available to filter the data, add ? to the end of the URL, followed by the parameter name using the underscore prefix:

https://fakerapi.it/api/v2/users?_quantity=2

This quantity parameter will set the number of users returned to be two.

JSON

The data we see in the browser may look a little messy, but when formatted it may look more familiar:

{
  "status": "OK",
  "code": 200,
  "locale": "en_US",
  "seed": null,
  "total": 2,
  "data": [
    {
      "id": 1,
      "uuid": "8995bc35-43c7-34b2-9061-33efcdd8e11f",
      "firstname": "Brittany",
      "lastname": "Cole",
      "username": "thaddeus70",
      "password": "r05#q8^7\u003C",
      "email": "[email protected]",
      "ip": "14.177.16.69",
      "macAddress": "F9:D4:09:9E:AF:2D",
      "website": "http://runte.com",
      "image": "http://placeimg.com/640/480/people"
    },
    {
      "id": 2,
      "uuid": "9b48245e-641e-3499-a654-b97734628fe1",
      "firstname": "Baby",
      "lastname": "Schimmel",
      "username": "gbayer",
      "password": "qiwOnB,O",
      "email": "[email protected]",
      "ip": "248.144.38.168",
      "macAddress": "1F:2C:B8:28:A3:B8",
      "website": "http://ankunding.com",
      "image": "http://placeimg.com/640/480/people"
    }
  ]
}

This structure is similar to objects we have previously covered. There are name/value pairs, and they are surrounded in curly braces. Although it looks like an object, it is called JSON (JavaScript Object Notation). The code syntax is based on a JavScript object, but it is usable with other programming languages too.

JSON is a lightweight format for sending data over the web. The JSON name/value pairs are surrounded in double quotes, and the data is sent as a string of text.

Fetching product data using the Fetch API

This product data from Faker will be used in our app. Just below the products array, add the following code:

const API_URL = "https://fakerapi.it/api/v2/products?_quantity=20";

function fetchProducts() {
    const response =  fetch(API_URL);
    console.log(response);
}
fetchProducts();
  • const API_URL =: This is a reference to the URL to fetch the products from Faker.
  • fetch(API_URL): The fetch() API is used to fetch a resource from a server or API, and stored into a response variable.

Try this in the browser and you will see something similar to Promise {<pending>}.

Promises and async/await

When we make a request for something external, such as from a server or API, we dont know exactly how long the response will take. There could be network issues causing slowness or the API could be down. To handle this, a JavaScript Promise is returned with the following outcomes:

  • Pending: initial state, no result yet.
  • Fulfilled: task completed successfully.
  • Rejected: task has failed.

We see the pending state because we log the result to the console immediately after performing the fetch operation. This log will run faster that it takes to retrieve the products information over a network. There is a way to wait for the response before proceeded by using async/await.

This involves adding the await keyword before the fetch. To enable this, we also need to mark the function as async:

const API_URL = "https://fakerapi.it/api/v2/products?_quantity=20";

// async function
async function fetchProducts() {
  // await data before proceeding
    const response = await fetch(API_URL);
    console.log(response);
}
fetchProducts();

You can find more information about async JavaScript, promises, and async/await in this section.

Parsing JSON

The console.log will now show a different result, similar to this:

body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "https://fakerapi.it/api/v2/products?_quantity=20"

Although we now get a result, it is not the same JSON data we had when pasting the URL directly into the browser. When receiving JSON from the Faker API, this string needs to be read/converted to a JavaScript object to work with. To do this, JavaScript has a built-in method available called parse():

async function fetchProducts() {
    const response = await fetch(API_URL);
    const data = await response.json();
    console.log(data);
}

The result is now strutured in the same way we had in the browser, with the products available in the data property:

code: 200
data: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
locale: "en_US"
seed: null
status: "OK"
total: 20

Setting products to use the API data

We currently generate products from our products array:

let products = [
    {
        name: "Stylish long-sleeve t-shirt in blue / medium",
        description: "A stylish long sleeve blue t-shirt, in size medium.",
        price: 20.95,
    },
    {
        name: "Stylish long-sleeve t-shirt in red / large",
        description: "A stylish long sleeve red t-shirt, in size large.",
        price: 21.95,
    },
];

Remove the contents of this array:

let products = [];

This will be replaced with the API data:

async function fetchProducts() {
    const response = await fetch(API_URL);
    const data = await response.json();
  // replace console.log:
    products = data.data;
}

Creating products from this products array is handled by the renderProducts() function. We are currently calling this function at the bottom of the script. Move this function call to be inside of fetchProducts():

async function fetchProducts() {
    const response = await fetch(API_URL);
    const data = await response.json();
    products = data.data;
  // move function call into here:
    renderProducts();
}

This will ensure the products are created after the API data is set.

Refresh the browser to see the 20 products from the API!