What is an API and how to call an API in JavaScript
Tags: javascript, beginners, layman
Published: 2020-05-10 11:12:51

Have you ever wondered what the heck is this term "API" that everyone keeps talking about? Or did your boss just throw another one of those "We might want to integrate XYZ Api into this project" and you are like, _What exactly is an API? Can someone please explain it to me in English?_

Don’t worry, I can try, and I bet you already know what it is in some vague way, but let's get it clear.

Let us first look at the word *API* itself.

![API](https://dev-to-uploads.s3.amazonaws.com/i/8ciw09c34yhf9frig6k1.jpg)

APIs stands for **A**pplication **P**rogramming **I**nterface
Lets first break up the word and understand all components individually

Application - An application that we are wanting to communicate with

Programming - Controlling or commanding

Interface - A way to communicate - (like switchboard at homes)

### Interface

Let's look a bit at **interface**, that is the main keyword over here. So interface is basically a predefined way to communicate or a medium to communicate between two parties. 

Let us take a simple example of a lightbulb. It is an object that needs to do something, it needs to illuminate the room, but it cannot do that whenever or however it wants to do. We need to tell it when we want it to be on or when we want it to be off. For that, we have an interface called *switch* which can help us tell what we want to the bulb in a way that both we and bulb understand. 

So the switch is an **interface** between us and bulb.

![Switch is an interface between us and bulb.](https://dev-to-uploads.s3.amazonaws.com/i/k2irjjvid855zatplh80.jpg)

Similarly, APIs are just interfaces from which we can control some applications. Usually, in software development, this is called programming (verb - to configure / control), so the interface is called an Application Programming Interface.

So, in simple terms, _*APIs are a way to communicate with an application*_.

In fact, in programming, we are continuously using APIs without even realizing that we are. Remember the first JavaScript "console" statement that we wrote, it was an API from the browser!

A web browser is an application that has a console. And we might feel that we are writing something to the console using console.log, but the truth is that we are never actually given direct access to the console. It is the browser's property and we are given an input in which we can write commands to say browser to print something to console. Basically, we use the console API to tell the browser what to write.

So hurray! 😃, you have already used an API, that should make you feel much more confident about yourself.

Now let's come back to the point why you are reading this article in the first place - To use an API in javascript.

Currently, COVID-19 is very much a hot topic so let's find some API for that and try to show its data on our page.

[Here is one such API (General Stats)](https://corona-virus-stats.herokuapp.com/api/v1/cases/general-stats)

In the browser, we have a function called fetch with which we can call external APIs via a network.

So the first step would be to fetch the data from API, so that is what we will tell the browser to do using the fetch function.

```jsx
fetch("https://corona-virus-stats.herokuapp.com/api/v1/cases/general-stats");
```

The fetch function returns a [promise](https://web.dev/promises/) which can resolve to response details or be rejected if some error occurs.

```jsx
fetch("https://corona-virus-stats.herokuapp.com/api/v1/cases/general-stats")
			//Response resolves to a readable stream, 
			//so this statement helps us convert it into 
			//a static object
			.then(response => response.json()) 
			//Now that we have the data, let us see what it looks like in console
			.then(responseData => {
				console.log(responseData);
			});
```

The output of the above code in a console would look like below:

```jsx
{
	"data": {
		"total_cases": "4,100,726",
		"recovery_cases": "1,441,474",
		"death_cases": "280,431",
		"last_update": "May, 10 2020, 01:29, UTC",
		"currently_infected": "2,378,821",
		"cases_with_outcome": "1,721,905",
		"mild_condition_active_cases": "2,331,138",
		"critical_condition_active_cases": "47,683",
		"recovered_closed_cases": "1,441,474",
		"death_closed_cases": "280,431",
		"closed_cases_recovered_percentage": "84.0",
		"closed_cases_death_percentage": "16.0",
		"active_cases_mild_percentage": "98.0",
		"active_cases_critical_percentage": "2.0",
		"general_death_rate": "7.000000000000001"
	},
	"status": "success"
}
```

The data that we receive is in JSON format so javascript makes an object from it (for this case and wherever the API returns a JSON response, but it might change depending on the API we use).
So we can use this response data as we use any other object, and this is a way to take output total cases on the console.
```jsx
console.log(responseData.data.total_cases);
```

Great, now we have learned how to get data and display it on the console from an API. So next time you hear the word API, just remember that you already know how to work with it, it is just a friendly URL with which your application can talk to either retrieve some data or send data or commands.

I have not covered any extra things like showing the data on the web page, that should be fairly easy if you know even the basics of javascript.

Now go explore some other APIs and add that to your resume :P

The fetch API is available from browsers natively, but there are also other ways to call an API like using third party libraries/helpers like [axios](https://github.com/axios/axios), [jQuery Ajax](https://api.jquery.com/jquery.ajax/), etc. Since you know the concepts now, they should not be hard to implement, just take a look at their documentation. You can also [read a detailed comparison of libraries](https://blog.bitsrc.io/comparing-http-request-libraries-for-2019-7bedb1089c83).

Apart from this, we still need to send data over to APIs and also need to _authorize ourselves_ as a client to a lot of APIs. 
We would cover those in upcoming articles, for now, play around with some open APIs available to get data like [JSON Typicode](https://jsonplaceholder.typicode.com/)
You can find [a good list of open APIs here.](https://github.com/public-apis/public-apis)

PS. This was my first article and I wrote it to explain a friend about APIs and I am looking forward to creating more content like this.
Do let me know if you found this article helpful and what else would you like to read about.

Credits:
Photo of switchboard by [twinsfisch](https://unsplash.com/@twinsfisch) on [Unsplash](https://unsplash.com/)
Images edited using [Canva](https://canva.com/)

Thanks for reading till the end!