Make Your First API Calls with JQuery AJAX

Beginner's guide to consuming endpoints via Frontend Javascript

The information age is over: we have all the information now. All of it. We're in a unique place in human history where we've somehow managed to mine more data than we know what to do with... and a lot of that data is easily accessible via APIs.

We're going to get our feet wet with REST APIs today, thus allowing us to interact with meaningful information. Making Ajax GET calls with JQuery is perhaps as basic as it gets: there's a good chance we already know all this stuff, but even I constantly forget the exact syntax of everyday functions. Chances are I'm going to come back to this post at some point just to copy and paste the snippets below.

Introduction to REST APIs

If you're new to executing AJAX requests, chances are you may be new to REST APIs in general. This crash course is going to be fast and rough around the edges, so strap in.

In the most simple sense, a REST API endpoint is a URL. It just so happens that this URL probably expects more from you than simply visiting it, and as a result, should output something useful for you. API Endpoints will almost always output either JSON or XML; these responses will give you information varying from error codes to the actual data you seek.

REST APIs expect requests to come in one of the following forms:

  • GET: A request looking for read-only data. Some GET requests simply need to be copy and pasted into a browser window to receive results, but usually we need to either authenticate or specify what we're looking for.
  • POST: A write request to the target resource. Expects that new information will come as a result of this request.
  • PUT: Updates pre-existing data somewhere, likely in some database.
  • PATCH: Somewhat similar to PUT, and in my experience rarely used at all.
  • DELETE: Expects that information will be deleted as a result of the request

If this all seems like new information, I'd highly recommend downloading Postman to become familiar with how API calls are structured.

For now, we'll focus on working with a simple GET endpoint.

Learning By Doing

If you've been checking out Snkia's roundup posts lately, you may have noticed nifty link previews being generated. To demonstrate how to make API calls via a frontend client with JQuery, we'll be walking through how to create link previews using the LinkPreview API. This service serves as a good tutorial because:

  • It's an example of a simple GET endpoint
  • There's a quick and immediately useful end result
  • It's free

Tell me That Ain't Insecurr

I want to stress here that we're doing this for the sake of learning; while this is probably the fastest way to start working with an API, it is most definitely not secure.

Making calls with private keys stored and passed via the client side exposes your key publicly. In a production environment, this is like shoving your password in people's faces. People will most definitely want to steal and exploit your private key: if what you were doing didn't have any value, it wouldn't require a key in the first place.

Hopefully this has scared you enough to consider passing credentials in the future. That said, there's another solid reason we selected LinkPreview as today's example. LinkPreview offers domain whitelisting for requests, so even if somebody did steal your key, they'd only be able to use it from your domain ;).

Make sure you whitelist the domain you'll be working from.

Fetch me Daddy

Go get started with an API key over at LinkPreview if you're following along. I'm going to assume you already have JQuery readily available from here forward.

To get started, we'll wait for our document to load, and set two critical variables: the API URL, and our API key.

$( document ).ready(function() {
  var api_url = 'https://api.linkpreview.net'
  var key = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' // not real
});

If you're following along what we've done with Lynx Roundups, our next step is to get all the relevant <a> tags on a page, loop through them, and replace them with their respective link previews.

$( document ).ready(function() {
  var api_url = 'https://api.linkpreview.net'
  var key = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' // not real
  
  $( ".content a" ).each(function( index, element ) {
      console.log($( this ).text());
  }
});

The JQuery .each method creates a loop which iterates over every element matching the provided selector. In our example, we only want <a> tags in the content of our page; otherwise we would get all links, like navigation links and so forth.

Now it's time to bring in that $.ajax() thing we've been going off about.

$( document ).ready(function() {
  var api_url = 'https://api.linkpreview.net'
  var key = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' // not real

  $( ".content a" ).each(function( index, element ) {

    $.ajax({
        url: api_url + "?key=" + key + " &q=" + $( this ).text(),
        contentType: "application/json",
        dataType: 'json',
        success: function(result){
            console.log(result);
        }
    })
  });
});

This is how Ajax request are structured: the contents of $.ajax() is essentially an object taking values it will use to construct the request. The above example is about as simple as it gets for making a barebones GET call. We're looping through each <a> tag and passing its contents (the url) to the API, and receiving an object in response.

Ajax requests can take way more parameters than the ones we just specified. I recommend reading over the JQuery Ajax documentation closely; not only for the sake of these requests, but understanding the potential items we can specify will solidify an understanding for REST APIs in general.

The line contentType: "application/json" specifies that the content coming back to us will be in JSON format - this is a very common header when dealing with REST APIs.

With any luck, your response should come back looking like:

{
    "title":"Google",
    "description":"Search webpages, images, videos and more.",
    "image":"https//:www.google.com/images/logo.png",
    "url":"https://www.google.com/"
}

If you'd like to use this in a meaningful way, feel free to do something like the mess I've put together below:

$( document ).ready(function() {
  var api_url = 'https://api.linkpreview.net'
  var key = '5b578yg9yvi8sogirbvegoiufg9v9g579gviuiub8' // not real

  $( ".content a" ).each(function( index, element ) {
    $.ajax({
        url: api_url + "?key=" + key + " &q=" + $( this ).text(),
        contentType: "application/json",
        dataType: 'json',
        success: function(result){
            $( element ).after(
            '<a href="' + result.url + '"> \n ' +
              '<div class="link-preview"> \n ' +
                '<div class="preview-image" style="background-image:url(' + result.image + ');"></div> \n ' + 
                '<div style="width:70%;" class="link-info"> \n ' +
                  '<h4>' + result.title +'</h4> \n ' +
                  '<p>' + result.description +'</p> \n ' +
                '</div><br> \n ' +
                  '<a href="' + result.url + '" class="url-info"><i class="far fa-link"></i>' + result.url + '</a> \n ' +
                '</div></a>');
            $( element ).remove();
        }
    })
  });
});

That template should serve you well for most GET API calls you're going to make via JQuery. Go wild and see what you can do to leverage APIs and expose some people's personal data or whatever.

See how I just created HTML by stringing together a bunch of ugly strings in Javascript? Don't do that; there are countless better ways to handle this, they just so happen to be out of scope for this post.

If we were to truly complete this example, we'd want to refine our logic to ensure we're not receiving nonsense. There's no validation on what's coming back in these calls, so there's nothing in place to protect us in the case that a page doesn't comply with our format.

Author image
New York City Website
Product manager turned engineer with an ongoing identity crisis. Breaks everything before learning best practices. Completely normal and emotionally stable.

Product manager turned engineer with an ongoing identity crisis. Breaks everything before learning best practices. Completely normal and emotionally stable.