Published: April 06, 2020, Edited by: Jakob Hastrup

Introduction to using a API in P5.JS

Why?

This guide is made by a student at Roskilde University. He experienced a high learning curve when entering computer science and one of the topics that was hard to understand was the relationship between frontend and backend development. This is also called client-side/server-side programming. A typical tool for linking the frontend with the backend is a Application Programmable Interface (API).

In this guide we will focus on how to use data provided by an API in a client side program. By doing this we hopefully ease the learning curve of working with this kind of software. Because there is a lot of hardcore guides in this topic, but many of those expects that you know what a JSON object is, how to reference variables in an array and what asynchronous programming is.

This guide is for you who don't know what we are talking about, but would like to explore some of the many open datasets of the internet. Even though this guide is supposed to be easy, we expect that you have tried to make some programs before.

We will make different parts about about how to use application programmable interfaces (API) on the client side. APIs is a way to communicate with a server through a request/response pattern. In the introduction we will learn to request data with a HTTP request, and what it is we receive as the response (JSON objects). We will also show how to reference the loaded data and we do this by showing images from an API in a P5.js software.

  • Introduction to API, JSON
  • Simple graphs based on JSON response (work in progress)
  • Advanced data visualisation (work in progress)

Introduction to using a API in P5.JS

The internet contains a lot of APIs with all kinds of data. We can discover everything from random pictures at https://picsum.photos/ to global data about Covid-19 development https://covid19api.com/. This github repository has a overview of public APIs https://github.com/public-apis/public-apis. They have APIs with no need of authentication, but some of them requires registration.

In this tutorial we will use complete open APIs only. That means you just need to make a request and then the information will be available in your program. The requests are HTTP requests, and most programming languages have libraries to do these kinds of requests.

To start very simple we will learn how to fetch a picture from https://picsum.photos/. In the end of this guide we have made this webapplication. It loads a list of JSON objects and shows one picture when clicking the mouse button, the image can then be changed by clicking a keyboard button.

HTTP request

We do this with a HTTP request. Many APIs has a documentation and we look into this to know how to make the right requests. In this guide we want a list of five pictures. Therefore we call the API by this HTTP request (try to click the link):

https://picsum.photos/v2/list?page=0&limit=5

This i a typical API call with:

  • A server.
  • A version.
  • A method.
  • Some parameters.

The server is picsum.photos and then the version is v2 (version 2). The method is list, because that's what we want to return, and then the page is 0 and the limit is 5. This means that we requests the 5 first pictures. A API call can therefore be generalized by this form

server/version/method?parameter1=x&parameter2=x  

JSON response

This link results in this in a response with this code inside:

[{"id":"0","author":"Alejandro Escamilla","width":5616,"height":3744,"url":"https://unsplash.com/photos/yC-Yzbqy7PY","download_url":"https://picsum.photos/id/0/5616/3744"},{"id":"1","author":"Alejandro Escamilla","width":5616,"height":3744,"url":"https://unsplash.com/photos/LNRyGwIJr5c","download_url":"https://picsum.photos/id/1/5616/3744"},{"id":"10","author":"Paul Jarvis","width":2500,"height":1667,"url":"https://unsplash.com/photos/6J--NXulQCs","download_url":"https://picsum.photos/id/10/2500/1667"},{"id":"100","author":"Tina Rataj","width":2500,"height":1656,"url":"https://unsplash.com/photos/pwaaqfoMibI","download_url":"https://picsum.photos/id/100/2500/1656"},{"id":"1000","author":"Lukas Budimaier","width":5626,"height":3635,"url":"https://unsplash.com/photos/6cY-FvMlmkQ","download_url":"https://picsum.photos/id/1000/5626/3635"}]

JSON Formatter

This is the JSON response in its raw format. This is maybe understandable for a trained programmer, but if there was a lot of data in the response we would rather have the parsed version. Therefore we recommend to install some kind of JSON formatter in your browser. Chrome users can install JSON Formatter. After installing a JSON formatter you should be able to see the objects like this instead (here we only show one out of 5):

{
"id": "1000",
"author": "Lukas Budimaier",
"width": 5626,
"height": 3635,
"url": "https://unsplash.com/photos/6cY-FvMlmkQ",
"download_url": "https://picsum.photos/id/1000/5626/3635"
}

This is a JSON object. And that's what we often get when we request APIs for data. A bracket scope with variable names, and then some data. This means that if we reference the download_url variable from this JSON object we get the link to a picture. This makes it possible to make a little webprogram that shows a picture from picsums server. We will do this in p5.js to show how to implement some data from a API into a client.

P5.js example

If you have never used P5.js and want to learn to use this, we can recommend Mads Hobyes tutorial: https://learn.hobye.dk/programming/P5JS_Basics
You can decide to use p5.js through an online editor or run it on a local server.
We will show you how to do it with the online editor.

Loading JSON from API with httpGet()

To load the JSON object into our client we use the method:

httpGet(path, [datatype], [data], [callback]).  

This means we need to specify a URL to pass to the path parameter. Therefore we load the information like this. For now we can do this in setup().

let url = ‘https://picsum.photos/v2/list?page=0&limit=5’  
httpGet(url, 'json', false, function(response) {  
          });

Callback function

The httpGet() method is now calling the API and returning the JSON object to the callback function. The callback function will only run, if the API request is a succes.
This is asynchronous programming. First time i did this i was confused. But it helped me to think of it as if a waiter is requested for food at a restaurant. The customer is not able to eat the food before the waiter has responded the request with food from the kitchen. The callback function is what happens when the API has fulfilled the request.

To see this working try to make the callback function print the JSON object. This is done by making a global variable load and declare it to the response. Then we can print the load which now reference the loaded JSON object.

let load;

let url = ‘https://picsum.photos/v2/list?page=0&limit=5’  
httpGet(url, 'json', false, function(response) {  
        load = response;
        console.log(load);
          });

If we do this we will see this in console:

This is because the response is a list of JSON objects. If you click the arrow you can click on arrows for each of the objects and reveal what they contain.

This is very similar to the datastructure of array. We have a list of objects that can have objects (or other arrays inside).

If you have trouble with programming this yourself, paste the code below (where i have also written the setup and draw functions, that we will use later) into your editor. From now on we run the request function by pressing the mouse.

let load;

function mousePressed() {

  let url = 'https://picsum.photos/v2/list?page=0&limit=5';
  httpGet(url, 'json', false, function(response) {

    load = response;

    console.log(load);

  });
}

function setup() {  
  createCanvas(windowWidth, windowHeight);
  imageMode(CENTER);
}

function draw() {

}

If you run this program and click the mousebutton, the program should fetch data from the picture API. When the data is fetched the load variable contains the latest response. The console.log(load) will print the contained JSON object in console.

If this works you have succeeded in fetching data via an API. If we want to use the data we need to reference the variables inside the object.
This is done like this.

load[0].download_url;  

Here we took the first object of the list and referenced the download_url (which contains the image we want to show).
So now we can make a global image variable called loadedImage and use the loadImage() method to declare it as the picture from the API.

let loadedImage;  

Inside the callback function of httpGet(), declare the variable. It's clever to do it inside the callback function, so we only declare a new loaded picture when we successfully load new data.

loadedImage = loadImage(load[0].download_url);  

Now we can draw the picture. This is done in the draw() function. But we have a problem because the picture should only be drawn, when there is a picture. Therefore we have a if statement based upon if there is a loaded picture.

background(0);  
if (loadedImage) image(loadedImage, width/2, height/2);  

New picture every time we click

Right now the program is a little boring, because it always shows the same picture. But luckily we are programming, so remember it is easy to add variables into HTTP requests or just expand the use of the JSON object. In this guide we retrieved 5 objects, so that is what we can draw. But the request can have a higher limit and we can scroll through those by changing the picture loaded.

First change the url limit to 100.

let url = 'https://picsum.photos/v2/list?page=0&limit=100';  

Add a pick global variable.

let pick = 0;  

And add a keyPressed() function:

function keyPressed() {  
  if(pick==load.length) pick = 0;

  console.log(pick);
  loadedImage = loadImage(load[pick].download_url);

  if(pick<load.length) pick++;
}

This function runs if a key is pressed and it loads a new picture based on the pick count. This variable increases in value by each keypress, and returns to zero if it gets out of bounds.
This is the full program that should fetch a list if the mouse is pressed, and then you can see the different objects by pressing a key.

Final code

The full code is below (or can be tried here). Ive added some text to credit the photographers (which also are retrieved from the JSON objects) and made it responsive to changes in windowsize.

let load;  
let loadedImage;  
let pick = 0;



function mousePressed() {

  let url = 'https://picsum.photos/v2/list?page=0&limit=100';
  httpGet(url, 'json', false, function(response) {

    load = response;
    console.log(load);
    loadedImage = loadImage(load[0].download_url);

  });


}

function keyPressed() {  
  if(pick<load.length)pick++;
  if(pick==load.length) pick = 0;
  text(load[pick].author,40,40);
  console.log(pick);
  loadedImage = loadImage(load[pick].download_url); 
}

function setup() {

  createCanvas(windowWidth, windowHeight);
  imageMode(CENTER);
  textAlign(CENTER, CENTER);
  fill(255);

}

function draw() {

  background(0);
  if(!loadedImage) {
    textSize(20);
    text("Press a mouse button to fetch the image list",(width/2),(height/2)-height/2.5);
  text("Press a key to go to next image in the list",(width/2),(height/2)-height/4);
  }

  if(loadedImage) {
     textSize(60);
    image(loadedImage, width/2, height/2, loadedImage.width/10, loadedImage.height/10);
    text(load[pick].author,(width/2),(height/2)-height/2.5);
  }
}

function windowResized() {  
  resizeCanvas(windowWidth, windowHeight);
}