Using API For Your Frontend Application

Using API For Your Frontend Application

Table of contents

I was talking to a friend who said he doesn't know what an API is, so I decided to write about how you can use an API to spice up your front-end application.

What is an API? API stands for Application Programming Interface and Wikipedia defines it, an Application Programming Interface (API) as a computing interface that describes interactions between multiple software intermediaries. On a lighter note, what this is saying is that API helps connect your web application to other web applications.

There about four popular ways of making an API call, we have :

  1. fetch
  2. Axios
  3. XMLHttpRequest
  4. jQuery

I would only explain how you can use fetch and Axios to make API call from (jsonplaceholder.typicode.com/users), let's get started.

# fetch fetch allows you to make a request to the server. The fetch method is not supported by old browsers but works perfectly well on our modern browsers (it can be polyfill though). When using call we can make an API call in two different ways.

First

fetch.png

So we have been able to console.log the data from API

Screenshot 2022-09-27 at 09.20.11.png

Second Alternatively, we can use our fetch method this way too.

fetch2.png

Results of the data we logged.

Screenshot 2022-09-27 at 09.20.11.png

A quick explanation of what is going on here.

So in the first line of our code, we created a variable that stores the URL of the API we want to request. In the second line, we started the fetch request with the fetch method. PS: the fetch method only takes two arguments, and the second argument is optional. If we only use one argument the request will default to a GET request; if we use the 2nd argument, we have access to all the other request types.

Finally, I would like you to look at the callback functions inside each of the .then() method invocations. Inside the first .then() we put: response => response.json() What this does is allow us to get access to our data from the second promise in the form of a JavaScript object. You need to include this part in your fetch request to get back the data you want as a result for you to use in the callback of your second .then()

Axios

Axios is an open-source technology for making HTTP requests and provides other great features. It can be used in plain javascript and other frameworks like reactJs, Vue.js, and even Angular. It supports all modern browsers.

How to install Axios:

if you are using one of the package managers maybe npm or yarn.

Npm install axios

Yarn add axios

You can also include it in your HTML file using:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

You can start sending HTTP request, when you include this script in your HTML file. Thus we have:

axios.png

One thing I like about Axios is the fact that it handles errors very well and Axios performs automatic transformations and returns the data in JSON format.