Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 10, 2020 11:12 am GMT

What is an API and how to call an API in JavaScript

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?

Dont 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

APIs stands for Application Programming Interface
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.

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)

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.

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

The fetch function returns a promise which can resolve to response details or be rejected if some error occurs.

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:

{    "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.

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, 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.

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
You can find a good list of open APIs here.

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 on Unsplash
Images edited using Canva

Thanks for reading till the end!


Original Link: https://dev.to/chintanpalan_53/what-is-an-api-and-how-to-call-an-api-in-javascript-ii

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To