DEV Community

Cover image for A Comprehensive Guide to APIs and the Fetch API
Gyau Boahen Elvis
Gyau Boahen Elvis

Posted on

A Comprehensive Guide to APIs and the Fetch API

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

What are APIs?

According to IBM, 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

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

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 valueproperty gets updated.

No need to worry about the value and onFulfilment array properties, since you won't ever use them.

Fetch API Promise Visualized

Implementing the Fetch API

fetch(URL, optional)
Enter fullscreen mode Exit fullscreen mode

The fetch API takes two arguments. The first argument is the URL to the resource we want to fetch - this is a compulsory.

fetch('https://www.example.com')
Enter fullscreen mode Exit fullscreen mode

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

fetch('https://www.example.com',{
     method:'post'
})
Enter fullscreen mode Exit fullscreen mode
  • Headers: This provides meta information about the user's request. This includes the time of request, size of request, content-type among others.
fetch('https://www.example.com',{
     method:'post',
     headers:{
         "Content-Type": "application/json"
     }
})
Enter fullscreen mode Exit fullscreen mode
  • 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.
fetch('https://www.example.com',{
     method:'post',
     headers:{
         "Content-Type": "application/json"
     },
     body:{
        "userName":"Gyau"
     }
})
Enter fullscreen mode Exit fullscreen mode

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 code of the response.

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

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
  }
)

Enter fullscreen mode Exit fullscreen mode

Example

In the code snippet below, we are making an API GET to the Random User API, this API helps generate random users for testing your application.

fetch("https://randomuser.me/api/")
Enter fullscreen mode Exit fullscreen mode

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.

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))
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
liligrvs profile image
tata

We'll go over the fundamentals of what an API is, how it functions, some real-world uses for it, and how it may enhance your business operations and customer experiences in this post.

Collapse
 
timothyolanrewaju profile image
Timothy Olanrewaju

This was a good read