Follow along with our fun and simple copy-and-paste tutorial on how to build your first API project. This hands-on guide will help you learn more about how APIs work and what you can build with the Clarifai API!

cassidyHello. Welcome. If you’re here, I’m assuming you haven’t used an API before. Me neither. Just kidding, I was trying to be relatable. I hope it worked.

Anyway.

This is a guide to help you use your first API. I work for Clarifai, so we’re going to use Clarifai because I’m very heavily biased. But also because the Clarifai API is simple, ridiculously easy to use, and most importantly, super cool.

Let's get started

This tutorial assumes you have nothing but a general understanding of what an API is. I like working with web projects, so we’re going to do a web project. If you like using other technologies, that’s cool too. What’s great about APIs is that they’re generic and can be used anywhere. So, if you follow along with this and understand the theory behind APIs, you can apply it to your own projects.

Okay, I said this was a copy and paste guide, and I meant it. We’re going to copy and paste everything. Open your terminal or command prompt.

If you’re on a Mac or Linux, type the following:

mkdir my-first-api
cd my-first-api
touch {index.html,index.js,keys.js}

If you’re on Windows, type the following:

mkdir my-first-api
cd my-first-api
type NUL > index.html
type NUL > index.js
type NUL > keys.js

Donezo.  Now, if you’re comfortable with the terminal, you can navigate through your files and stuff there. Or you can open your Finder or Explorer (or whatever that thing is that lets you look at your files) and do it all there.

In your editor of choice (use whatever you want, I use vim, some use Atom, some use Sublime … do what you want), paste the following in your index.html file.  The HTML doesn’t really matter in this project, so it’s pretty minimal.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>My first API</title>
  <script type="text/javascript" src="keys.js"></script>
  <script type="text/javascript" src="index.js"></script>
</head>
<body>
</body>
</html>

Lovely.  You have a <head> that references your JS files that you created. There’s also an empty body.  

Oftentimes, the first thing you need to do when you use an API is get your credentials.  Not all APIs require this, but most do.  API credentials are very similar to usernames and passwords of your accounts on various sites, like FarmersOnly.com or Xanga.

Since we’re going to use Clarifai, we have to get our creds from there.  Go to developer.clarifai.com and sign up.  Once you’ve done that, click your name to get to the “Manage your Applications” page and hit, “Create a new Application”.  Go ahead and name it whatever you’d like.

image00

You’ll then be directed to a page that looks like this:

image01

And would you look at that. That’s your Client ID and Client Secret.  Let’s put them to good use.

Go back to your favorite editor and open up keys.js.  In there, copy and paste the following (only replace my Client ID and Client Secret with your own):

var CLIENT_ID = 'asdasdasdasdQ';
var CLIENT_SECRET = 'asdfasdfa';

Boom.  Now, you might be wondering, why do we have a file that just has these variables in it, why not just put these variables in the index.js file?  Well, my darling, that’s because of security.  It’s always better to put your keys in a file that you don’t put online (assuming you’re going to push this project online) so that people don’t take your keys.  Why would someone take your keys?  Well, for the same reason why they’d take your keys to your car: it gives them access to your stuff.  If someone got ahold of your Client ID and Client Secret, they could use up credits on your account or do things on your behalf.  We don’t want that.

The way APIs work is similar to regular web addresses.  When you go to a URL in your browser, you get a webpage returned to you.  When you send a request to an API endpoint with code, you get a response returned to you.  Different APIs return different responses.  If you’re curious about this, you can go to https://api.clarifai.com/v1/tag/ in the browser.  

You’ll get something that looks like:

{"status_code": "TOKEN_NONE", "status_msg": "Authentication credentials were not provided in request."}

This is your response!  Right now it’s not returning anything useful because we need to set it up with your Client ID and Client Secret.

Let’s get to actual coding.  We need to figure out what we want our app to do.  In case you haven’t heard what Clarifai is or does, you should look it up.  But in summary, the API lets you get tags for a given image.  So, we can make a quick little web app that lets the user put in an image URL and see the tags for that image.  Simple enough.

In your index.html, add this line in the <head> before the keys.js import:

<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>

This line imports axios.  It’s a library that makes getting information from APIs easier.  You don’t necessarily *need* this library, but it makes for less code.

The next thing you need to do is get an access token.  An access token is kind of like a session, like when you log into Gaia Online and you stay logged in for 30 days.  To get an access token, we’ll need to ping Clarifai’s /v1/token endpoint.  Copy and paste this into your index.js file:

Copy and paste this into your index.js file:

function getCredentials() {
  var data = {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET
  };
  var url = 'https://api.clarifai.com/v1/token';

  return axios.post(url, data, {
    'transformRequest': [
      function() {
        return transformDataToParams(data);
      }
    ]
  }).then(function(r) {
    localStorage.setItem('accessToken', r.data.access_token);
    localStorage.setItem('tokenTimestamp', Math.floor(Date.now() / 1000));
    // yolo
  }, function(err) {
    console.log(err);
  });
}

function transformDataToParams(data) {
  var str = [];
  for (var p in data) {
    if (data.hasOwnProperty(p) && data[p]) {
      if (typeof data[p] === 'string'){
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
      }
      if (typeof data[p] === 'object'){
        for (var i in data[p]) {
          str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p][i]));
        }
      }
    }
  }
  return str.join('&');
}

Whoa there.  What’s all this?  I’ll tell you.

The getCredentials() function first builds an object called data, and that object has your Client ID and Client Secret, and labels itself as client credentials.  Then, we have a variable url that has our endpoint URL, https://api.clarifai.com/v1/token.  And then finally, we use axios to make a POST request where we pass in our data and our url, and we call transformDataToParams().  Quickly switching gears, the transformDataToParams() function simply transforms that data object to something that axios will understand.  Let’s jump back.  The .then() functions that are called after the axios function are what happens after the information is collected from the /v1/token endpoint.  Inside these, we gather the access token and save it to local storage, the current time, and in the next function, we log the error if there is one.

I know that was a lot. But you’ve got this.

So, now we have an access token.  That means we can use that to get some tags for photos now! Now, at the end of index.js, paste this in:

function postImage(imgurl) {
  var accessToken = localStorage.getItem('accessToken');
  var data = {
    'url': imgurl
  };
  var url = 'https://api.clarifai.com/v1/tag';
  return axios.post(url, data, {
    'headers': {
      'Authorization': 'Bearer ' + accessToken
    }
  }).then(function(r) {
    // PARSE HERE
  }, function(err) {
    console.log('Sorry, something is wrong: ' + err);
  });
}

This is very similar to getting an access token.  Our function first takes in imgurl (which is just a variable name for image URL), then it gets the access token from local storage and assigns it to a variable.  Then we make a data object with the passed in imgurl variable, and finally we make a url variable again only this time, it’s linking to the /v1/tag endpoint.  We shove all of this into another axios call, where we pass in url, data, and we make a headers object that uses the access token.  We also have the .then() functions, just like before, where the first one will do something with the response, and the next one will log the error.  Let’s make that first function do something!

At the end of your file, paste this in:

function parseResponse(resp) {
  var tags = [];
  if (resp.status_code === 'OK') {
    var results = resp.results;
    tags = results[0].result.tag.classes;
  } else {
    console.log('Sorry, something is wrong.');
  }
  return tags;
}

This function, parseResponse(), is nothing super fancy.  It literally just parses the response so that we just get the tags.  If you look at the documentation for the /v1/tag endpoint and you go to the Responses section, you’ll see that there’s a lot of mumbo jumbo that we don’t need for this particular application.  So, the parseResponse() function checks that the status_code is OK (which means everything ran smoothly), and then just cuts out everything until we get the specific tags we want.

So, we should now go back to our postImage() function, and go to the comment that says PARSE HERE and replace the comment with this line:

parseResponse(r.data);

This gives parseResponse() our retrieved data, and gets our tags for us!

Now that we have all of this up and running, we just have to connect our functions together.  What we need to do is first check if we have an access token.  If we do, great, we can easily get the tags then.  If we don’t, or if it’s expired, we need to call getCredentials() and then we can get the tags.

At the bottom of the file, paste this in:

function run(imgurl) {
  if (Math.floor(Date.now() / 1000) - localStorage.getItem('tokenTimeStamp') > 86400 || localStorage.getItem('accessToken') === null) {
    getCredentials();
  } else {
    postImage(imgurl);
  }
}

Boo yah.  This function takes in an image URL, then checks if there’s an expired/nonexistent access token, otherwise calls postImage().  Done.

Or are we?

We’re not.  Ha.  Fooled ya.  If you look closely, once getCredentials() is called, nothing happens.  You get your token, but you never call postImage() once you have it. This looks like a job for CALLBACKS.

Inside that if statement in the run() function, replace getCredentials() with this:

getCredentials(function() {
  postImage(imgurl);
});

We’re having the getCredentials() function take in postImage() so that it can call it once it’s finished.  Now we have to edit the getCredentials() function so that it can accept and call this function.

So, go to the method signature of getCredentials() and replace it with this:

function getCredentials(callbackFunction) {

Now we have access to this function within getCredentials().  Now, go to the comment that says “yolo” (yeah that’s right, it was there on purpose) and replace that line with:

callbackFunction();

Oh man.  That’s it.  We’re connected.  Now let’s actually have something call these functions.  Go to index.html and paste this in the <body>:

<div>
    <input type="text" id="imgurl" placeholder="Image URL"/>
    <button onclick="run(document.getElementById('imgurl').value)">Get tags!</button>
</div>

This just adds a little form where you can paste an image URL in the input, and when you click the button, you should get the tags.

But now, we need to actually put the tags somewhere.  Add this line after that <div> you just added:

<div id="tags"></div>

This is where our tags will be printed.  Now go back to index.js, scroll to the parseResponse() function, and paste in this line just above the return statement:

document.getElementById('tags').innerHTML = tags.toString().replace(/,/g, ', ');

This line gets that <div>, then adds our parsed tags to it, separated by commas.

Alright, I think we’re done here!  It’s not beautiful (you can style this page with whatever CSS you want) but let’s see it work.  Go back to your terminal and run a server.  If you don’t know how, here’s a simple way that works for all OSes (requires Python to be installed on your system):

python -m SimpleHTTPServer 8000

Or if you’re using Python 3:

python -m http.server 8000

Now go to your browser and go to localhost:8000, and try out an image URL!  Voila!

Wow.  You did it.  You used your first API.  Congratulations.  If you got lost along the way, I conveniently have all the code here on GitHub. Or, if you don’t want to write all of this yourself ever again, Clarifai has some great API clients for a bunch of languages like Java, Javascript, Python, Go, etc.

Hope you had a good time following along.  If you didn’t, you probably don’t know what fun is.  If you’d like to ask me or anyone at Clarifai more questions about the API, feel free to tweet us at @clarifaidev and we’ll get back to you ASAP!

Peace out girl scout, thanks for reading!

"Follow this awesome copy+paste guide to your first API project with@cassidoo @clarifai 💯 http://bit.ly/1U48hyt"