A Comprehensive Guide to APIs and the Fetch API
Tags: api, javascript, fetch, webdev
Published: 2023-09-08 20:29:15

## Introduction
Have you ever wondered how Shazam instantly recognizes a song once a snippet is sent to it?🤔 How about, how Facebook automatically display your Instagram photos? The concept behind these amazing technological feats is not about your device storing every song or image in the world, but rather the fascinating concept of APIs (Application Programming Interfaces).

In this article, we will embarking on a journey to explore the inner workings of APIs, understand their various architectural types, and appreciate why mastering them is a neccessity in the world of software development. We'll specifically dive into the Fetch API, a JavaScript method that acts as a bridge between your applications and external servers, enabling seamless communication.

Buckle up and lets dig deep into this amazing concept together.
 
![Excitement](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h1e11xtsinkaem8kb4cl.gif)


## What are APIs?

> [According to IBM](ibm.com/topics/api), An API, or Application Programming Interface, is a set of defined rules that enable different applications to communicate with each other. It acts as an intermediary layer that processes data transfers between systems, letting companies open their application data and functionality to external third-party developers, business partners, and internal departments within their companies.

The API is just the waiter that sends your order to the chef and then gets the food for you when it is ready. In this scenario, we are assuming that the chef is our server and you, the one making the order: the client. The waiter acts as the API-(mediator) between the client and the server, allowing communication between these two parties.

![Image of how APIs work](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cba6spi80klwxj0uyheu.jpg)

## Types of API Architectures
APIs are categorized according to the set of protocols they follow, which govern the allowed data formats and commands. Significant APIs among these classes are stated below:

**1. REST API**
Representational State Transfer API is the most popular and widely used API today. It exchanges data using HTTP requests. This API follows the REST Guidelines, and a few of them are given below.

- `Client Server Interaction`: Client-server interaction should take the form of a request from the client and a response from the server. The server is never allowed to make a request, and the client, never allowed to make responses.

- `Uniform Interface`: To ensure interoperability between any client and any server, all requests must use HTTP as the communication format. All server responses must be in JavaScript Object Notation format.

- `Stateless`:  The interaction between a server and a client is distinct from all other interactions. Servers don't store any data from past interactions.

**2. SOAP**: These APIs employ the Simple Object Access Protocol to send data across a network. It uses XML to encode data across the network. It specifies exactly how data should be shared across a network. When compared to REST APIs, this makes it very safe for data exchange. Because of its rigorous constraints, this API is more difficult to implement and thus less popular among developers. It is usually used for internal data sharing, which necessitates a high level of security. The Amazon Web Services API is an example of a SOAP API.

**3. GraphQL**: Graph Query Language empowers clients to request only data they require, making it easier to evolve APIs over time and enabling strong developer tools. Given that we're using GitHub's API, you could use GraphQL to get only usernames or repository descriptions without receiving additional data apart from the ones requested. These APIs are efficient and boost application performance.

## Why Master APIs

Over 10,000 APIs were made available for public use by businesses in 2013, which is four times more than there were in 2010. You can probably guess how many APIs are currently available. 
With so many companies making investment in APIs, possessing a deeper understanding of API becomes a necessity in the software industry.

API is an essential part of the world we live in today. They are used everywhere on the internet, from using them to perform simple activities such logging in or signing up to your account with third party applications such as Google or Apple to integrating payment systems like PayPal or messaging systems into your applications as a developer. They also form the backbone of complex applications such as Spotify, Netflix and X (Twitter) among others.

[![Every day applications of APIs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lrvyvz61pzgb0ay2lyev.png)
](https://www.turing.com/kb/7-examples-of-APIs)

## The Fetch API

Fetch API is used to fetch resources over a network. It is the JavaScript method that is used to make requests to servers. It provides a flexible interface, making it very easier for our applications to communicate with servers. 

_How does the fetch API work?_ 
The fetch API is a promised based method, that is: anytime we use the fetch API it returns a Promise object. 

This Promise Object is more like a real-life promise in where we commit to doing something and, as a result, make a promise; in the end, it is either the promise we made is fulfilled and resolved or it is failed and rejected. This is exactly how JavaScript Promises work, too. 

The Promise Object has three states: 
🔃 `The pending state`: Promise is neither Fulfilled nor rejected
✅ `The Fulfilled`: Operation successfully carried out
❌ `The rejected state`: Operation failed.
 
The Promise Object comes with two hidden properties: `value` and  `onFulfilment array`. The value property keeps the response object from the server, and the `onFulfilment array` stores the function(s) we wish to call after receiving the response object. These functions are added to `onFulfilment array` using the `.then()` method and are called immediately as soon as the `value `property gets updated.

No need to worry about the `value` and `onFulfilment array` properties, since you won't ever use them.
         
![Fetch API Promise Visualized ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ulv3r42dhwg8t9l3gzgm.gif)

## Implementing the Fetch API

```javascript
fetch(URL, optional)
```
The fetch API takes two arguments. The first argument is the URL to the resource we want to fetch - this is a compulsory. 

```javascript
fetch('https://www.example.com')
```

The second argument is optional, and it contains additional information we want to add to the URL. The additional information include

- Methods: This tells the server the action the client wants to perform. They include

`GET` - Retrieve resource from server. This is the default method if no method is stated.
`POST` - Ask server to create new resource
`PUT` - Update resource on server
`DELETE` - Delete resource on server

```javascript
fetch('https://www.example.com',{
     method:'post'
})
```
- Headers: This provides meta information about the user's request. This includes the time of request, size of request, content-type among others.

```javascript
fetch('https://www.example.com',{
     method:'post',
     headers:{
         "Content-Type": "application/json"
     }
})
```

- Body: This where data the client wants to send to the server is included. Unlike the headers and methods with strict rules on how to include them, in the body the user is at complete liberty to include whatever they want.

```javascript
fetch('https://www.example.com',{
     method:'post',
     headers:{
         "Content-Type": "application/json"
     },
     body:{
        "userName":"Gyau"
     }
})
```

The server returns a `response` which is then resolved to the response object. This object comes with several properties which could be used to check the status of the response from the server. Some of these properties include the `ok` property which will have a value of `true` if the request was successful, the `status` property which holds the [HTTP Status response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) code of the response.

The `catch()` method holds the function to be called when the promise is rejected.

```javascript
fetch('https://www.example.com',{
     method:'post',
     headers:{
         "Content-Type": "application/json"
     },
     body:{
        "userName":"Gyau"
     }
})

.then(response =>{
      if(response.ok){
         // Handling response
       }else{
        // Do something else
       }
      
   }
)
.catch(error=>{
        // function to run when promise is rejected
  }
)

```

## Example

In the code snippet below, we are making an API GET to the [Random User API](https://randomuser.me/), this API helps generate random users for testing your application.

```javascript
fetch("https://randomuser.me/api/")
```

The `then()` method in the code snippet below uses the `.ok` property to determine whether the request was successful. If it was not, it throws an error; however, if it was, it uses the `.json()` method on the Response object to parse the response body as JSON. 

```javascript
fetch("https://randomuser.me/api/")
.then(response=>{

     if(!response.ok){
        throw new Error("Failed")
     }
        return response.json()
})

.then(data => console.log(data))

.catch(error => alert(error))
```
The JSON body of the response object is passed as an argument to the next `.then()` method. Then it is processed as specified in the function body. In the code above, we just console log the data to the console. 

During the fetch or the processing of the response from the fetch API, if any error occurs, it is passed to the `.catch()` to handle the error.


## Conclusion
API is an essential part of the software engineering industry, and possessing a deeper understanding of what it is and how to use the fetch API to integrate and sync systems together is a necessity in this field. I hope this article gives you a proper introduction to the concept of APIs and the fetch API. A tutorial by freeCodeCamp has been linked at the bottom of this article for further studies.

Happy coding out there, guys. Peace Out✌️

![Happy coding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gy6g87dernxeuucqnaph.gif)


{% embed https://www.youtube.com/watch?v=WXsD0ZgxjRw&t=314s %}