How the #$@& Do I Use an API?! – Wikipedia API Basics

Wikipedia API Basics

1. So… What’s an API?
2. There’s an API For That!
3. Okay, I Know What an API Is…Now What?
4. Let’s Do It!
5. It worked! (Hopefully)

How the #$@& Do I Use an API?!

I’m taking a break from the WordPress development topic to delve into APIs. (Yay!)

I’ll be using the Wikipedia API for this example.

1. So… What’s an API?

APIs—application programming interfaces—are the current standard in utilizing information and technologies on the web. As taken from Wikipedia:

Just as a graphical user interface makes it easier for people to use programs, application programming interfaces make it easier for developers to use certain technologies in building applications. By abstracting the underlying implementation and only exposing objects or actions the developer needs, an API reduces the cognitive load on a programmer.

Sounds pretty damn useful. Without a technical example, though, the concept will likely seem very abstract if you’ve never used one before. (And we’re getting to that!)

2. There’s an API For That!

To give you a more concrete idea of what an API is and what you might use it for, here is a list of the types of APIs available (though this is by no means a comprehensive list):

Basically, just about any type of online resource or technology you can think of has an API.

3. Okay, I Know What an API Is…Now What?

Once you have decided on an API (or maybe a few) that you’d like to use, you’ll likely find that there is extensive documentation on what the API can do.

When I was first learning how to use APIs, though, the most difficult part for me was finding the actual code showing how to implement it!

I understood the API, how it worked, and what I could do with it, but WHERE THE HELL IS THE CODE SHOWS ME HOW TO DO IT?!

I was surprised at how difficult it was to find just that.

How you use APIs will differ between languages, of course.

It took me some time just find applicable examples of API calls.

Unauthenticated vs. Authenticated API Calls

Most APIs allow both unauthenticated and authenticated API calls. Unauthenticated will be more limited as far as what you can do.

For example, with an unauthenticated call to the Twitter API, you can display a timeline of tweets with the tag #MontyPython.

With authenticated API access, you can tweet your favorite Monty Python quote.

monty python tweet pythonquotes twitter wikipedia api basics
@pythonquotes

4. Let’s Do It!

We’ll start with unauthenticated API calls. We’re going to do a basic search of Wikipedia.

Here’s an example in plain ol’ JavaScript, courtesy of @gf3 (Gianni Chiapetta):

/* script.js */

var loadJSONP = (function(){
  var unique = 0;
  return function(url, callback, context) {
    // INIT
    var name = "_jsonp_" + unique++;
    if (url.match(/\?/)) url += "&callback="+name;
    else url += "?callback="+name;

    // Create script
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Setup handler
    window[name] = function(data){
      callback.call((context || window), data);
      document.getElementsByTagName('head')[0].removeChild(script);
      script = null;
      delete window[name];
    };

    // Load JSON
    document.getElementsByTagName('head')[0].appendChild(script);
  };
})();

<!-- index.html -->

<html>
  <head>

  </head>
  <body>
    <script src="script.js"></script>
    <script>
      loadJSONP(
        'https://en.wikipedia.org/w/api.php?action=opensearch&search=monty+python',
        function(data){
        	console.log(data);
        }
      );
    </script>
  </body>
</html>

And an example using jQuery:

<!-- index.html -->

<html>
  <head>

  </head>
  <body>
    <script src="jquery.min.js"></script>
    <script>
    $.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&callback=?&suggest=true&search=monty+python', function(json){
      console.log(json);
    });
    </script>
  </body>
</html>

My example is using the Wikipedia API, with the hard-coded search of Monty Python. If you test out this code, you’ll see that the output looks something like this:

search wikipedia api basics json

5. It worked! (Hopefully)

So now I’ll use a simple example to do something with this code besides printing it to the console.

Javascript:

<html>
  <head>

  </head>
  <body>
    <table id="results">
    </table>
    <script>
    // Credit to @gf3 (Gianni Chiapetta) for this snippet: https://github.com/gf3

    var loadJSONP = (function(){
      'use strict';

      var unique = 0;
      return function(url, callback, context) {
        // INIT
        var name = "_jsonp_" + unique++;
        if (url.match(/\?/)) url += "&callback="+name;
        else url += "?callback="+name;

        // Create script
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;

        // Setup handler
        window[name] = function(data){
          callback.call((context || window), data);
          document.getElementsByTagName('head')[0].removeChild(script);
          script = null;
          delete window[name];
        };

        // Load JSON
        document.getElementsByTagName('head')[0].appendChild(script);
      };
    })();
    </script>
    <script>
      loadJSONP(
        'https://en.wikipedia.org/w/api.php?action=opensearch&search=monty+python',
        function(data){
          console.log(data);
          // If results are found
          if(data[1].length > 0) {
            // Titles of Results
            var title = data[1];
            // Descriptions of Results
            var description = data[2];
            // Links to Results
            var link = data[3];
            // Table to Hold Results
            var table = document.getElementById('results');

            // Iterate through results
            for(var i=0; i<data[1].length; i++) {
              var elemHTML = '<tr><td>' + title[i] + '</td><td>' + description[i] + '</td><td><a href="' + link[i] + '">View Article</a></td></tr>';
              document.getElementById('results').innerHTML += elemHTML;
            }
          }
          else console.log('results not found');
        }
      );
    </script>
  </body>
</html>

View on GitHub Pages

jQuery:

<html>
  <head>
  </head>
  <body>
    <table id="results">
    </table>
    <script src="jquery.min.js"></script>
    <script>
    $.getJSON('https://en.wikipedia.org/w/api.php?action=opensearch&callback=?&suggest=true&search=monty+python', function(json){
      console.log(json);
      // If results are found
      if(json[1].length > 0) {
        // Titles of Results
        var title = json[1];
        // Descriptions of Results
        var description = json[2];
        // Links to Results
        var link = json[3];

        // Iterate through results
        for(var i=0; i<json[1].length; i++) {
          $('#results').append('<tr><td>' + title[i] + '</td><td>' + description[i] + '</td><td><a href="' + link[i] + '">View Article</a></td></tr>');
        }
      }
      else console.log('results not found');
    });
    </script>
  </body>
</html>

View on GitHub Pages

And this is what you should see:

wikipedia api basics search results json

Here’s a simple, but prettier example:

kimberlythegeek wikipedia api basics search app json javascript jquery

View on GitHub Pages

You can view all of the code used in this article on my GitHub repo.


APIs can be difficult to get the hang of in the beginning. As always, if you run into to problems, remember to Google that Shit!

Don’t give up if it’s difficult or frustrating! Challenging yourself is the best way to learn and to grow.

Thanks for reading!

/kimberly

Syntax Highlighting by EnlighterJS

About the Author

Kimberly is a software engineer, and currently works as a Test Engineering Intern for Mozilla.

While she always enjoys learning new technologies, her current focus is python, and when she has free time (she doesn't), Angular & Node.

When not coding, Kimberly spends time with her three young boys in Durango, CO.


One Reply to “How the #$@& Do I Use an API?! – Wikipedia API Basics”

Comments are closed.