API through the Eyes of a Beginner
Tags: api, webdev, beginners
Published: 2023-02-13 12:42:31

First Things First..

1. This article has no prerequisites except the Request-Response Cycle which I have described in my previous [Blog](https://dev.to/crazycoder122/a-beginners-guide-to-http-https-2hj2).

1. This Article may seem a little bit longer and may seem a bit boring but once you get through it, I gurantee that you will never regret your time and would be at least conceptually familiar and confident in the field of API, and you can easily get that push within yourself to build one of your own.

## Introduction to APIs:
So what on earth is **Application Programming Interface(API)** ?

Application Programming Interface(API) , as the name suggests, is an **_Interface_** over which we can build our Application.

Now this may seem a bit complicated. So, let’s break it down!

Basically, API can be seen as a piece of code which has already been written by someone to be used by others for making their Applications.

That piece of code can be easily used in our application (without us being concerned on how the hell the internal mechanisms are going on!!) and which provides lots of data or functionalities.


![API Meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z86nqur15wrnstgy2vqr.jpg)

## Types of APIs:
Formally we do not differentiate APIs in the way I am now going to explain. But for the in-depth understanding maybe I feel its a lil bit easy..

So, do you think that the term API is related with Web?

If Yes, then maybe this section is mostly meant for you.

The correct answer being No!! Though Web APIs are mostly talked about but there are also other kinds of APIs.


> **Framework APIs:**

So, let’s say you are building a Mobile App and you wanna add some functionality which involves _camera_. Now how will you access the Camera within your code and achieve the intended functionality?

There comes the use of Framework APIs. The Android Framework provides us with a **Camera API** which can be used to access the Camera and get the most used functionalities like clicking pics, etc. readymade.

You can explore a lot about Framework APIs by searching with the following topics like **React Context API**, **Javascript Fetch API**, **React Component API**. If you get stuck in any of these, just hit me up once.. Will be more than happy to help!!

> **Web APIs:**

Since, you have come until this blog, so I am assuming that you have a basic knowledge about the definitions and differences between _Frontend_ and _Backend_.

So, Web APIs are basically used to connect our _Backend_(Server Side Functionality) with the Fronted we are building. Our Backend may consist of very _complex data operations_, _user authentications_ etc. which needs to be integrated with the Frontend and there comes the role of APIs.

Basically, Web APIs is like a Messiah which saves a lot of work and finally we can build a website, which is _Dynamic_ in terms of Data.



![Web API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gepkh3h1ozlack0k0ay7.png)

## Types of Web APIs:
Primarily Web APIs can be classified into 2 types:

1. **_SOAP_ APIs** (Simple Object Access Protocol)
1. **_REST_ APIs** (Representational State Transfer)

In today’s scenario, REST APIs are much widepread in the industry than SOAP APIs due to a number of reasons like **Support for variety of contents including _JSON_ and _XML_**(the only content type supported by _SOAP APIs_), **performance**, etc.

Throughout this Blog, our main focus will be on REST APIs.


![SOAP vs REST](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wv84z5k8kfm9yml0eqwb.jpg)

## REST APIs and its Components:
REST APIs are the backbone of today’s Web Industry. They operate over **HTTP and HTTPS Protocol**.

They support a lot of content type like **Text/HTML**, **JSON**, **Image** etc.

REST APIs are always **Stateless**, i.e. , the backend server does not have to keep track of the previous requests to validate and send/receive data for the current request.

The **Return Type** of the current Request is decided _on-the-fly_ depending on the info provided through the URL and the Body(explained in the later part of this Blog)

Enough of the Theoretical Aspect of it!!

Now let’s focus on the Practical Part of APIs and try to understand the exact anatomy of it.

It consists of mainly _6 main components_:

#### 1. An Endpoint:
The REST APIs operate over **_URIs_**(_Universal Resource Identifier_) to fetch and store informations from the server and there comes the play of **Endpoint**. We know that every server has their own fixed **domain names** attached to them like [www.google.com](www.google.com), [www.medium.com](www.medium.com) etc.

On top of that, we see a /(**Forward slash**) followed by some _big address_ and that is the **Endpoint** itself.

The **Domain name** helps us to locate the Server and the endpoint helps us to locate some **particular specific resource** within that server.

Let’s understand it through an example..

> Your friend lives at 21B Burdwan Road,Alipore, Kolkata-700003.
Now to reach his house is it sufficient to know that he lives in **Kolkata**?
Nope!! You need to know his full address.
So, here **_Kolkata_** is like the **_Domain Name_** and the **_rest of his address_** is the **_Endpoint_**.

![Endpoint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3mjqqzoidl376r8zba91.jpg)


#### 2. A Method:
This is one of the most important component of the REST APIs.

It specifies the **Mode of Operation** to be performed by the API on the server-side for this Incoming Request.

The Methods which are mostly talked about are:

- **_GET_** (Get the Resource)

- **_POST_** (Create a new Resource)

- **_PUT_** (Update a Resource) ,

- **_PATCH_** (Almost similar to _PUT_)

- **_DELETE_** (Delete a Resource)

- **_OPTIONS_** (Get all the allowed Methods for the Particular Endpoint).

Now, the most interesting part of it is that we can achieve all these Methods using only 1 single method and that is **POST**. Every Method (except **OPTIONS**) can be implemented using POST Request.

Then the Question arises, why we are learning so many Methods? Would simulating all the other types of Requests using POST break my API?

The answer is **NO**. You can successfully achieve every Method using POST but the problem comes with **scalability**.

When you have to deal with _numerous endpoints and Resources_, it becomes a horrendous task to maintain a bunch of POST requests.

Instead if we can categorise the Requests using the Methods, the code becomes much **cleaner** and **managable** easily.

Also, it makes much more of human sense to use a DELETE Method to delete a Particular Resource in the server than to naively sending a POST Request.


![API Method](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bs96pe87hbk9thr9wlzm.jpg)

#### 3. Headers:
Ever Inspected an API Call through browser? If Yes, then at least once, you have been terrified by the bunch of _Headers_ sent and received while making that call and wondered about their usage.

Coming to the point of their applications, there are a lots. But generally speaking, the Headers simply define _how the API Response should be and other stuffs_.

Some of the few common Headers are:

1. **Content-Type:** It specifies the _type of data_ that client must expect from the server side so that it can render it properly. Common values include **“Text/HTML”**, **“Application/JSON”** etc.

2. **Authorisation Headers:** These headers serve as the carrier of **Authorisation** and **Authentication** information to the servers. The _Auth Token_ or the **Bearer Token** is sent from the client to the server. If the credentials are found to be valid, then the server returns the desired Response else throws an _“Unauthorised”_ Response.

3. **Cache-Control:** It simply defines the **caching policy of the server** and till how much time the client can rely on the _pre-fetched data_ before it gets stale.

```
access-control-allow-credentials: true
access-control-allow-headers: X-Playlog-Web
access-control-allow-origin: https://ogs.google.com
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
cache-control: private
content-encoding: gzip
content-length: 131
content-type: text/plain; charset=UTF-8
cross-origin-resource-policy: cross-origin
date: Tue, 07 Feb 2023 21:28:10 GMT
expires: Tue, 07 Feb 2023 21:28:10 GMT
server: Playlog
x-frame-options: SAMEORIGIN
x-xss-protection: 0

```

#### 4.Body:
This is the most Important part of any API. It basically contains the whole _chunk of data_ sent from the client to the server.

> _For Example, while creating a new Resource using POST Request, we specify the details of the Resource to be created through the Body of the API. The Server then fetches the whole request body, manipulates it accordingly and thereby stores it in the Database._

```
{
  "name" : "John Doe", 
  "age" : 30,
  "gender" :"Male"
}
```

#### 5. Parameters:

> _Not to be confused with Endpoint. They may seem similar but they are not functionally!!_

Endpoints take us to the specific resource but for **further clarification** and **filtering**, we need the **Query Parameters** to be passed with the URL.

Let’s get back to the previous example..

> _You have reached your friend’s house successfully using his **Residential Address**(**Endpoint** in this scenario). His family consists of 5 members.
What would you do to meet your friend among all the members? You will tell his name.
And there comes the **Query Parameters(Friend’s name in this case)** . You have reached a particular location in the server where there are many resources. Now you want to do some specific operation with some specific Resource. You just have to clarify that to the server using **Query Parameters**._


![Query Parameters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bpgv0dp2225fxgfnx6lk.jpg)

#### 6. Status Codes:
All of us, whether a Web Developer or not, have at least once faced the **_404 PAGE_** in life. Isn’t it frustrating? But have you ever wondered why we call it as 404 and not anything else?

What is so special about this number (except it being a Palindrome Number lol!!) ?


![404 Error Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xm3nzecogxvyyw3kltpf.jpg)

Till now, we have got to know about the whole journey of an API call almost. But when the _Response_ is sent from the server to the client, does it contain only the raw chunk of Data and Headers? or something else is embedded in it?

Yes.. Some **_Numeric Codes_** are embedded within the Response to specify whether the call has been successful or not. If **unsuccessful**, then the codes also provides us a deep insight as to _on what ground did the request fail_?

For all of the Status Codes and their meanings, refer to [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)


![HTTP Status Codes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5kc1hklcqghyfrg94rpm.jpeg)

I Guess now you are confident enough over the Topic of **APIs** and maybe aspiring to make one of our own. For any kind of Doubts, don’t ever hesitate to contact me for clarification.

Hope that you enjoyed reading through the Article.

Feedbacks are welcome.

Have a Good Day :) :)

Image Courtsey — **Google Images**