How to connect to an API in JavaScript ?
Last Updated :
08 May, 2020
An
API or Application Programming Interface is an intermediary which carries request/response data between the
endpoints of a channel. We can visualize an analogy of API to that of a waiter in a restaurant. A typical waiter in a restaurant would welcome you and ask for your order. He/She confirms the same and carries this message and posts it to the order queue/kitchen. As soon as your meal is ready, he/she also retrieves it from the kitchen to your table. As such, in a typical scenario, when a client endpoint requests a resource from a resource server endpoint, this request is carried via the API to the server. There are a various relevant information that are carried by the APIs which conform to certain specification of schema such as that provided by
OpenAPI,
GraphQL etc. This information may include endpoints URL, operations(GET, POST, PUT etc), authentication methods, tokens, license and other operational parameters. APIs most commonly follow the
JSON and
XML format as its key mode of exchanging request/response while some also adhere to the
YAMLformat.
Mostly the response generated by a resource server is a JSON schema which carries the state information of the resource requested at the other endpoint. As such these APIs have been named REST APIs where REST stands for REpresentational State Transfer. The state of the resources can be affected by the API operations. It should also be noted that there are System APIs as well which are used by the operating system to access kernel functions. A common example would include the Win32 API which is a windows platform API and acts as a bridge for system level operations such as File/Folder select, button styling etc. Most programming languages which have GUI libraries are wrapped upon this layer.
Sample Request of an API(Google Geolocation API) :
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 311,
"radioType": "gsm",
"carrier": "airtel",
"considerIp": "true",
"cellTowers": [
{
"cellId": 22,
"locationAreaCode": 115,
"mobileCountryCode": 310,
"mobileNetworkCode": 311,
"age": 0,
"signalStrength": -40,
"timingAdvance": 12
}
],
"wifiAccessPoints": [
{
"macAddress": "00:25:9e:ff:jc:wc",
"signalStrength": -33,
"age": 0,
"channel": 12,
"signalToNoiseRatio": 0
}
]
}
Sample response:
{
"location": {
"lat": 41.1,
"lng": -0.1
},
"accuracy": 1200.2
}
The schema, usage pricing, etc of an API is dependent on the organization providing the API. There are freely available APIs such as PageCDN API, as well pay as you go pricing model based APIs such as Street View Static API. APIs enable a client/programmer to use the infrastructure and cloud services of an organization to get access to various resources over the internet. An API usually requires an API key(unique) along with a few optional credentials for it to authenticate a resource request made by a client. Web Programmers often rely on APIs for pulling off various awesome tricks such as displaying filtered tweets via twitter API on their homepage, converting HTML to pdf via HTML2PDF API, etc. For science students and enthusiasts, various APIs such as NASA APIs(Exoplanet, Insight, etc) provides content on demand. Mobile app developers also use APIs to a great extent such as weather APIs, Geolocation, Google Analytics API, etc.
Connect to an API using JavaScript:
To make API calls using JavaScript, a reference can be made under the <script> tag to the JavaScript library which contains functions and other configuration parameters pertaining to the API should be made. A good API always maintains appropriate documentation to its functions and parameters. In most cases, this js library is made available via the Content Delivery Network(CDN) in order to be responsive. JavaScript contains functions for serializing and de-serializing a JSON object and thus handling JSON responses and traversing/parsing the response is also managed within the same script.
The below snippet shows the simplest example of using google visualization API to construct a chart from data
present in google sheets(spreadsheet).
A reference to the js library containing necessary functions is made as follows:
html
<script type="text/javascript"
src=
"https://www.gstatic.com/charts/loader.js">
</script>
javascript
google.load('visualization', '1',
{
'packages':['corechart', 'table', 'geomap']
}
);
google.setOnLoadCallback(drawGID);
function drawGID() {
//var queryString = encodeURIComponent('SELECT A, B LIMIT 5');
var query =
new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/spreadsheetId/gviz/tq?range=');
query.send(handleQueryResponse);
}
var resp;
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() +
' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
resp = response;
var chart =
new google.visualization.LineChart(
document.getElementById('any_div_or_container'));
chart.draw(data, { height: 400, curveType: 'function',
legend: { position: 'bottom' }});
}
The above code contains a callback function that fires when the window is loaded. A query string containing the spreadsheet ID and other parameters is passed to the server. Here spreadsheetId needs to be replaced by the spreadsheet id of the concerned spreadsheet. The 'any_div_or_container' string is to be replaced by the DOM element on which we wish to display the results in our page. The response handler analyses the response and checks the content type after which it parses to the data to produce the desired output. The above code is run with a sample spreadsheet which generates a JSON response as shown below:
gvjs_rl {wva: "0.6", qX: "ok", hv: Array(0), Sw: Array(0), O2: "1651350667", …}
wva: "0.6"
qX: "ok"
hv: []
Sw: []
O2: "1651350667"
R: gvjs_L
$p: null
Ff: Array(2)
0: {id: "A", label: "", type: "datetime", pattern: "M/d/yyyy H:mm:ss", p: {…}}
1: {id: "B", label: "", type: "number", pattern: "General"}
length: 2
__proto__: Array(0)
eg: (98) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, ...]
Fr: null
cache: []
version: "0.6"
__proto__: gvjs_$k
__proto__: Object
Output Screenshot of sample Line chart:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read