Query an API

An API (Application Programming Interface) is the way that two computer programs communicate and share information with each other.

For instance, when you log in to DIY how does it get all of your projects and favorites on your portfolio? All of the information for your account is stored on a big, hard to read database on the server. Programers create API's to translate the data from a server into something more standard and easy for clients (be it your browser or mobile app) to use.

api

The same API provides the information www.diy.org and the DIY App need. If the API is open (called an open API) or a user has acess (with an API key) to it, they can build something with the same exact data. You can view an API, too. The format is called JSON (JavaScript Object Notation) and looks like this:

    {
        "head": {
          "code": [HTTP response code],
          "status": [HTTP response message],
          "url": [HTTP request path],
          "method": [HTTP request method],
          "stamp": [ISO timestamp]
        },
        "response": {
          [Response object]
        }
    }

Query DIY's API

We've created an API key that will give you acess to our API. BOOM! A query to an API is when you request (aka ask for) information from it.

Install Node.js module to format JSON in Bash

JSON is easiest to read when it's indented correctly. Unfortunately, Bash doesn't do that by default (it will just fill your screen with letters and numbers that are really hard to read!). But fortunately there is a Node.js module that will! A lot of people have written small modules to handle common tasks with Node.js. The library of these tools is called NPM, Node Packaged Modules. At npmjs.org you can search all of the handy things people have made.

We'll install this module -g, which means globally, so that we can use it for more than just one project:

sudo npm install -g json

A Basic API Request

cURL allows you to send information in a URL syntax. Then we give it our API key, then tell it where the API we want is. Lastly, we use | json to tell use the json module we've installed that will format the json.

curl -H "x-diy-api-key:DIY_MAKER_KEY" https://brain.diy.org/ | json

You should see something like this:

basic request

Specific Request

Let's ask for 3 DIY Skills:

curl -H "x-diy-api-key:DIY_MAKER_KEY" "https://brain.diy.org/skills?limit=3&offset=0" | json

DIY has a site set up just for developers using our API. Visit friends.diy.org/developers to learn more about our API.