How to connect to an API in JavaScript ?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type="text/javascript" 
        src=
</script>

chevron_right


filter_none

edit
close

play_arrow

link
brightness_4
code

      
    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(
      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' }});
    }

chevron_right


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:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.