Working with APIs using Javascript

Published by: 2

Rookie

As a beginner, I found making HTTP requests a difficult concept to wrap my head around. Below is me asking a clueless question on stack overflow. Needless to say, I learned my lesson about the danger of asking question’s poorly.

In this tutorial, I will cover the basics of how to work with API’s using Javascript.  It’s my goal to write plainly, and without complexity in order to broaden the scope of new developers that this tutorial aims to help.

Setup – this is important

I took the liberty of creating a repo to help you visualize the process.  You can download it or clone it, and we should be ready to get started!

Getting Familiar With HTTP

There are 4 HTTP methods,  but most of the time you are going to be dealing with two of them

  • GET – A GET request allows you request data from a server.
  • POST- A POST request allows you to submit data to a specific server.

If you’re anything like me, you probably skipped all my jabbering above and are looking through the code, in order to figure things out. The repo contains three files index.html, myscript.css, and mystyles.css. Below is the full script for myscript.js

// IGNORE THIS CODE -  it is just here to make response a litle easier to read as oppose to black text. 
//but if your curious how this works - shoot me an email gregborrelly@gmail.com 
if (!library)
   var library = {};

library.json = {
   replacer: function(match, pIndent, pKey, pVal, pEnd) {
      var key = '<span class=json-key>';
      var val = '<span class=json-value>';
      var str = '<span class=json-string>';
      var r = pIndent || '';
      if (pKey)
         r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
      if (pVal)
         r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
      return r + (pEnd || '');
      },
   prettyPrint: function(obj) {
      var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
      return JSON.stringify(obj, null, 3)
         .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;')
         .replace(/</g, '&lt;').replace(/>/g, '&gt;')
         .replace(jsonLine, library.json.replacer);
      }
   };


// This get function is called everytime you press submit button. 
function get(){
    // Gets the value you selected for your method. 
    var method = document.getElementById("method");
    method = method.options[method.selectedIndex].value;

    // Gets the username you typed. 
    var user = document.getElementById("user").value;

    // Grabs the chosen endpoint 
    var endpoint = document.getElementById("endpoints");
    endpoint = endpoint.options[endpoint.selectedIndex].value;

    // Now we are ready to format the endpoint; 

    switch(endpoint){

        case "https://api.github.com/users/":
            endpoint = endpoint + user; 
            break
        case "https://api.github.com/users/{user}/repos":
            endpoint = "https://api.github.com/users/" + user +"/repos";
            break;

    }
  
    // Displays the endpoint url after is formatted - this is next to "RESPONSE for"
    document.getElementById("url").innerHTML= "<b>Response for:</b>" +  endpoint ;

    // Here we write out AJAX request
    $.ajax({
        url:endpoint,
        type:method,
        success:function(Response){
            // document.getElementById("code").innerHTML =JSON.stringify(Response);
            $('#code').html(library.json.prettyPrint(Response));
        },
        error:function(Error){
            $('#code').html(library.json.prettyPrint(Error));
        }
    });




}

 

Endpoints – making our first GET request.

Whenever you are looking to get data, you should be thinking in terms of endpoints. Endpoints are nothing but specific paths to the data you want to obtain. This brings up the question. How do I know what endpoints to use? The answer to that question is in the documentation for the API you’re using.  For example, in order to get data from a specific  user, one of GIT’s endpoints is /users/{name of user}

This is how it would look with the base of the API included: https://api.github.com/users/{replace this with name of user}

 

$.ajax({

 url:"",
 type:"",
 success: function(response){





};


});

The $.ajax function above is taking in an object with three parameters:

  • URL – This is going to be our endpoint(https://api.github.com/users/{replace this with name of user}).
  • type – This is where you specify the HTTP method, in the case of the above endpoint we are making a GET request in order to get data about the user.
  • Success – instead of taking a string, the success maps to a function.
  • Error – Also takes a callback function.

Something to keep in mind while reading this tutorial is that I  included the Jquery library in this project. The $.ajax() function is a jQuery function and won’t work unlesss you included the library in your HTML.

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title> GIT API</title>


    <link rel="stylesheet" href="mystyles.css">
    <script src="myscript.js"></script>
    <link rel="stylesheet" href="lib/prism.css">
    <script src="lib/prism.js"></script>

<!-- Including JQUERY library --> 
    <script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>

  <script>
  


  </script>

</head>

 

Callbacks and Asynchronicity

HTTP requests are asynchronous – meaning a request is sent out, and the program continues to execute until it receives a response. Because we don’t know when the response is going to come back, it is not possible to write code in a linear way.

Linear Code:  A Happens -> B happens -> C happens

instead, we use something known as a callback function.

Async Code:  A sends request  -> B happens -> A responds – passes response to callback function – > C happens

If that doesn’t make sense, that’s ok, we are going to have a more concrete example by going over the program ‘s flow of execution, in order to show how the code executes.

Understanding How The Program Flows

Let’s run through the flow of execution to better understand what’s happening.  When you clicked the submit button, our get() function got called.

<button onclick="get()">Submit</button>

The first thing the get() function does is grab the values from the input fields and assigns them to three different variables: method, user, endpoint.

// Gets the value you selected for your method. 
var method = document.getElementById("method");
method = method.options[method.selectedIndex].value;

// Gets the username you typed. 
var user = document.getElementById("user").value;

// Grabs the chosen endpoint 
var endpoint = document.getElementById("endpoints");
endpoint = endpoint.options[endpoint.selectedIndex].value;

Once the values are assigned, the program continues by formatting the endpoint in order to match it to what GIT is expecting. We do this using a switch statement.

switch(endpoint){

      case "https://api.github.com/users/":
          endpoint = endpoint + user; 
          break
      case "https://api.github.com/users/{user}/repos":
          endpoint = "https://api.github.com/users/" + user +"/repos";
          break;

  }

Then we display our formatted endpoint

  
  
// Displays the endpoint url after is formatted - this is next to "RESPONSE for"
 document.getElementById("url").innerHTML= "<b>Response for:</b>" +  endpoint ;

Now we get to the fun part, we are going to create out HTTP request by passing it our endpoint, method, and callback functions.

$.ajax({
     url:endpoint,
     type:method,
     success:function(Response){
         // document.getElementById("code").innerHTML =JSON.stringify(Response);
         $('#code').html(library.json.prettyPrint(Response));
     },
     error:function(Error){
         $('#code').html(library.json.prettyPrint(Error));
     }
 });

Guess what happens next?  our program continues to execute while the GIT API responds, so the next line in our program, get’s executed.

document.getElementById("code").innerHTML="Loading...";

Once the API responds, either your success or error callback function will run. The function that executes will add the response body into the screen replacing the loading word.

success:function(Response){
        // document.getElementById("code").innerHTML =JSON.stringify(Response);
        $('#code').html(library.json.prettyPrint(Response));
    },
    error:function(Error){
        $('#code').html(library.json.prettyPrint(Error));
    }

 

What’s Next? 

Now that you have data, is time to manipulate it. Stick around for part 2 of this tutorial, and learn how to work with objects, and manipulate a JSON response.

 

Want to learn more?

 

Leave a Reply

2 Comments on "Working with APIs using Javascript"

Notify of
avatar
Sort by:   newest | oldest | most voted
Petar
Guest

Nice article. However, since the article is aimed towards beginners I would suggest to explain the code in more detail, since it’s written for beginners.

A line such as this one var jsonLine = /^( *)("[w]+": )?("[^"]*"|[w.+-]*)?([,[{])?$/mg; is going to be difficult for beginners to comprehend.

Keep up the good effort 🙂

wpDiscuz