DEV Community

Ankita
Ankita

Posted on

How to use API with Fetch API and Promises.

A big part of working with JavaScript is learning how to connect to the API. As a new developer, at times you may just be asked to "play with some APIs"! To learn what they are and how to work with them. We're going to make a very simple advice generator web app with plain JavaScript that will retrieve information from an API and display it on the page.

PREREQUISITES

Basic knowledge of HTML and CSS.
Basic knowledge of JavaScript syntax and datatypes.
Basic knowledge of working with JSON and JavaScript objects.

GOALS

We are going to write from scratch random advice generator app that connects to Advice Slip API, retrieves the data with JavaScript, and displays it on the front end of a website.

It will look like this:

Image description

Quick overview:

What is an API?
APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols. An API is simply a medium to talk to program. For example, the weather bureau’s software system contains daily weather data. The weather app on your phone “talks” to this system via APIs and shows you daily weather updates on your phone.

Let's make it more clear with our vanilla JS DOM Element Example:
If You want HTML Elements in the JavaScript world you tell the browser to give that elements but how the browser will understand your language? it is done by using the querySelector API. Using document.querySelector API you can talk with the browser to give that particular element to me so I can make changes in it.

What is HTTP Request?
HTTP Requests are messages which are sent by the client or user to initiate an action on the server. HTTP works as a request-response protocol between a client and server.

Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

You may be familiar with the concept of a CRUD app, which stands for Create, Read, Update, Delete. Any programming language can be used to make a CRUD app with various methods. A web API uses HTTP requests that correspond to the CRUD verbs.

HTTP Method : POST => Creates a new resource
HTTP Method : GET => Retrieves a resource
HTTP Method : PUT/PATCH => Updates an existing resource
HTTP Method : DELETE => Deletes a resource

Let's get started.
We want to read data from our Advice Slip API so we are going to use HTTP GET method.

Let’s begin by creating a index.html file that contains some basic information, in order to render a page.

If I open this index.html page, I should see black page.

basic Index.html
Let’s now create our index.js file, which is referenced inside our html file.

how to referenced index.js file inside index.html

Inside our index.js file fetch data from the advice slip API and log the response

fetching data from api

What is Fetch API?
The Fetch API is a simple interface for fetching resources. Fetch allows us to make network request and handle responses easier than our old friend XMLHttpRequest(XHR). One of the main differences is that Fetch API uses Promises.

The fetch function takes one mandatory argument, which is the path to the resource you want to fetch and returns a Promise that resolves to the Response of that request.

What is Promise?
A JavaScript Promise object can be:

  • Pending
  • Fulfilled
  • Rejected

The Promise object supports two properties: state and result.

While a Promise object is "pending" (working), the result is undefined.
When a Promise object is "fulfilled", the result is a value.
When a Promise object is "rejected", the result is an error object.

When making an HTTP request as an asynchronous operation, fetch will not return any data. However it will return a response promise. When we log the response, it will show this Promise is in pending state. This means that the HTTP response we are expecting will get back eventually, but at the time of logging, this response was not ready to be logged.

Our Promise is in pending state, it can now transition into a fulfilled state if everything goes well or a rejected state if there’s an error while fetching. Once the Promise is settled, it can’t no longer change state.

Let’s now move back to our example and learn on how we can extract some data from this response Promise object. We will use the Promise.prototype.then method in order to attach a callback once our Promise has been fulfilled.

Image description

Image description

Now that we know our API response is working, we want to move on and actually get the body of the response. We want to call the json() method on the response in order to get the response body in json format. This operation is also asynchronous. The json() method actually returns a Promise, so we will need to create a Promise chain.

We will pass the value we receive from the first Promise into our chain in order to do some operations.

Image description

Once you refresh your browser and check your logs, you will see a object with key that contain attributes.

Image description

Now we can add it to our html element and get advice in front end.
we have used window.onload it is used to launch certain functions whenever a web page is loaded. Here we are loading advice when web page is loaded.

Image description

Image description

Top comments (0)