CodeNewbie Community 🌱

Cover image for Two simple ways of calling an API
Cristina {💡👩🏻‍💻}
Cristina {💡👩🏻‍💻}

Posted on • Updated on • Originally published at cristina-padilla.com

Two simple ways of calling an API

If you are learning how to interact with 3rd-party APIs, you are at the right place. In this post, I am sharing with you a project with two different but very simple versions of calling an API.

First of all, what is an API? It is literally defined as Application Programming Interface and it allows a website to communicate with another one and access its information.

I built a simple but fun Advice App, based on this Frontend Mentor challenge. It uses the Advice Slip API to generate random quotes of advice.

Advice App overview

See the final project here.

There are different ways of calling an API but I used the following:

  • Fetch
  • Axios

Fetch

Also known as fetch Web API takes a URL and always returns a promise, as the request of going through the internet takes some milliseconds. This promise resolves with a response, which will be executed in the future when the fetch request has been completed. This callback always takes an argument (a response).

As the browser doesn't know the response's format, we need to convert it manually to JSON with the .json() method.

response.json() also returns a promise, which means, we can't read the data immediately. We need to resolve the promise first with another .then(callback) instead. The variable data is the information we get from the URL, which can be an array or an object.

Fetch code example

In our case, if we log data, we will see the following object.

See the whole challenge solution here.

Axios

Axios is an open-source library that allows you to make HTTP requests easily. In order to use it, you have to install it (with npm) or copy the cdn in your project's head:

Axios link

The syntax is very straightforward. We define the api URL and call it with Axios, which includes a response:

Axios code example

See the whole challenge solution here.

Who would like to build a fun Advice app and give these tricks a try?

Latest comments (0)