How to connect to FakeJSON’s API using pure JavaScript

Trying to wrap your head around JavaScript and how to use APIs can be a little overwhelming at times. I wrote this tutorial to show what’s possible with the FakeJSON API even if coding is not your strong suit. Hopefully you’ll be able to make full use of the FakeJSON API and get a sense of what it’s capable of.

Tutorial Goal

I will be showing you how to use FakeJSON with pure JavaScript to create the test data for a web page. Take this as more of a proof of concept rather than a comprehensive in depth article on APIs and web development. We will cover:

  • What is a web API
  • What the FakeJSON API has to offer
  • How to connect to the FakeJSON API by making a HTTP POST request using JavaScript
  • How to use the FakeJSON response to create and display HTML elements

Finished Tutorial Product with FakeJSON

Finished Tutorial Product with FakeJSON Data

FakeJSON can create avatars using awesome Robo Hash service.

Finished Tutorial Product without FakeJSON

Finished Tutorial Product without FakeJSON Data

Prerequisite

This tutorial is ideal for those with at least some basic knowledge of HTML, CSS and JavaScript. If you’re just starting out, it may be a good idea to check out some of these resources beforehand.

What is a web API?

An API (Application Programming Interface) is the way a certain piece of software communicates to another piece of software. It is sort of like the command centre for the software, with the ultimate goal of making it easy for anyone to program with it.

A web API is really just one of many types of APIs. It is an API intended for access over the web using HTTP protocols. There would also be a defined response structure depending on the HTTP request. Put simply, a web API defines what can be expected when making a HTTP request. For this tutorial, we’ll be using the FakeJSON web API to make a HTTP POST request to a URL endpoint which will return us fake data in JSON format.

What can you do with FakeJSON API?

Tons (or less than tons depending on your subscription plan). You can:

  • Fake your backend as you work on your front end functionality – use HTTP methods, receive specific response status codes, incorporate delays, specify custom headers, utilize broken strings
  • Generate all types of fake test data using predefined or custom fields based on the format and name of your choice
  • Utilize resources through the saved resources feature – save your favorite API requests and reuse them easily

Refer to the documentation page for the full lowdown.

The basic setup

We will be creating an employee page with a fake user avatar, a fake first name, a believable but made up job title and a short nickname for the employee. Each made up employee will be displayed as a card in a simple grid format.

Let’s start off by creating a folder to store all the necessary files (three files really). This folder will contain the HTML file (index.html), CSS file (style.css) and the JavaScript file (scripts.js). The HTML file will look pretty simple and bare bones.

					              
<!DOCTYPE HTML>
<html lang="en">

  <head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<title>FakeJSON star lineup</title>

	<link href="https://fonts.googleapis.com/css?family=Roboto:500" rel="stylesheet">
	<link href="style.css" rel="stylesheet">

  </head>

  <body>

	<div id="root"></div>

	<script src="scripts.js"></script>
  </body>

</html>
					              
				            

The CSS file (called style.css) contains a bunch of different styling and design stuff. You don’t really need it to display the FakeJSON data. They just look nicer with them in it.

					              
* {
  box-sizing: border-box;
  width: 100%;
  padding: 10px;
}

h1 {
  text-align: center;
}

html {
  font-family: 'Roboto';
  background: #209CEE;
}

#root {
  max-width: 1000px;
  margin: 0 auto;
}

img {
  display: block;
  margin: 1rem auto;
  max-width: 100%;
}

p {
  padding: 0 2.5rem 2.5rem;
}

.container {
  display: flex;
  flex-wrap: wrap;
}

.card {
  margin: 1rem;
  background: white;
  box-shadow: 2px 4px 25px rgba(0, 0, 0, .1);
  border-radius: 12px;
  overflow: hidden;
  text-align: center;
  transition: all .2s linear;
}

.card:hover {
  box-shadow: 2px 8px 45px rgba(0, 0, 0, .15);
}

@media screen and (min-width: 600px) {
  .card {
	flex: 1 1 calc(50% - 2rem);
  }
}

@media screen and (min-width: 900px) {
  .card {
	flex: 1 1 calc(33% - 2rem);
  }
}
					              
				            

The rest of the tutorial will be focused on creating the JavaScript file. The final JavaScript file will look like this:

					              
var app = document.getElementById('root');

var container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);

var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
	"nameFirst": "nameFirst",
	"personAvatar": "personAvatar",
	"jobTitle": "personTitle",
	"nickName": "personNickname",
	"_repeat": 9
  }
});

var request = new XMLHttpRequest();

request.onload = function(){
  var fakeData = JSON.parse(this.response);

  if (request.status >= 200 && request.status < 400) {
	fakeData.forEach(companyRole => {
	  var card = document.createElement('div');
	  card.setAttribute('class', 'card');

	  var elem = document.createElement("img");
	  elem.setAttribute("src", companyRole.personAvatar);
	  elem.setAttribute("height", "180px");
	  elem.setAttribute("width", "100%");
	  elem.setAttribute("alt", "Profile Picture");

	  var h1 = document.createElement('h1');
	  h1.textContent = companyRole.nameFirst;

	  var p1 = document.createElement('p1');
	  p1.textContent = companyRole.jobTitle;

	  var p2 = document.createElement('p2');
	  p2.textContent = 'Also known as "' + companyRole.nickName + '"';

	  var br = document.createElement("br");

	  container.appendChild(card);

	  card.appendChild(elem);
	  card.appendChild(h1);
	  card.appendChild(p1);
	  card.appendChild(br);
	  card.appendChild(p2);
	});
  } else {
	console.log('You shall not pass');
  }
}

request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");
request.send(data);
					              
				            

How to connect to the FakeJSON API

Remember that documentation page, keep it handy. Open it in a new window if you have to as we’ll be referencing it throughout the remainder of this tutorial. You may have noticed that the documentation covers how to connect to the API using curl, jQuery, Ruby, Node, Python or Go. Alas, no plain ol JavaScript. Which gives this tutorial the perfect material to cover.

Obtaining your token

The first thing we’ll do is to obtain the FakeJSON token. This token is unique to your account and authorizes your usage of the API. If you don’t already have a token, you can get one easily by signing up here

Selecting the API endpoint

Every API request to FakeJSON will be directed to the FakeJSON API endpoint, app.fakejson.com/q. You have the flexibility of choosing either http://app.fakejson.com/q or https://app.fakejson.com/q depending on your use case.

Making a HTTP POST request

The HTTP request defines the response from the API. In our case, it specifies the fake data we would like to receive. Let’s start by connecting to the FakeJSON API. We’ll be using XMLHttpRequest objects, a way for us to interact with the FakeJSON server. We’ll be making a request for 9 array elements, each containing first names (titled nameFirst), an avatar (titled personAvatar), job titles (titled jobTitle) and nicknames (titled nickName). I’ve named these titles arbitrarily. You are free to name them however you like. However, you would have to follow the format of the fields based off the API documentation.

We'll be:

  • Creating a variable that stores the request payload following the FakeJSON request structure
  • Creating a variable that stores the XMLHttpRequest object
  • Initializing the request – specifying that the request is a POST and adding the URL endpoint
  • Sending the request along with the payload
  • Accessing the JSON response generated from the request
					              
var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
    "nameFirst": "nameFirst",
    "personAvatar": "personAvatar",
    "jobTitle": "personTitle",
    "nickName": "personNickname",
    "_repeat": 9
  }
});

// Create a variable that stores the XMLHttpRequest object
var request = new XMLHttpRequest();
request.withCredentials = true;

// Initialize the request – specify that the request is a POST and add the URL endpoint
request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");

// Send the request
request.send(data);


request.onload = function(){
  // Access the FakeJSON response - in JSON.
  var fakeData = JSON.parse(this.response);
  console.log(fakeData);

}
					              
				            

Using the generated JSON response

We can perform a simple test to check that the API connection is valid and to get a better sense of the data we’re working with. In the “Access the JSON response …” portion of the code, we’ll be converting the JSON response to a JavaScript object using JSON.parse() and printing its output onto the browser console with console.log().

					              
request.onload = function(){
  // Access the JSON response generated from the request
  var fakeData = JSON.parse(this.response);
  console.log(fakeData);
}
					              
				            

View index.html in the browser and open up the browser console. You should be seeing 9 JavaScript objects; each object with its job title, first name, nickname and avatar.

Optional step

If your subscription plan includes HTTP status codes, you can even add support in your code for status code handling. 200s are successful requests whereas 400s or 500s are generally caused by some type of error.

To deal with erors, we’ll just wrap the code in a simple if statement. The code will proceed with its execution if the status code falls between 200 and 400 or will output a message to the console if the if statement fails.

					              
request.onload = function(){
  // Access the JSON response generated from the request
  // Conduct status check. We're doing some stuff for valid requests and a customary message for an invalid request.
  if (request.status >= 200 && request.status < 400) {
    var fakeData = JSON.parse(this.response);
    console.log(fakeData);
  else {
    console.log('You shall not pass');
  }
}
					              
				            

Here’s what we have so far. The code with error handling.

					              
// Create a variable that stores the request payload
var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
    "nameFirst": "nameFirst",
    "personAvatar": "personAvatar",
    "jobTitle": "personTitle",
    "nickName": "personNickname",
    "_repeat": 9
  }
});

// Create a variable that stores the XMLHttpRequest object
var request = new XMLHttpRequest();

// Initialize the request – specify that the request is a POST and add the URL endpoint
request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");

// Send the request along with the payload
request.send(data);

request.onload = function(){
  // Access the JSON response generated from the request
  // Conduct status check. We're doing some stuff for valid requests and a customary message for an invalid request.
  if (request.status >= 200 && request.status < 400) {
    var fakeData = JSON.parse(this.response);
    console.log(fakeData);
  else {
    console.log('You shall not pass');
  }
}
					              
				            

The code without error handling.

					              
// Create a variable that stores the request payload
var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
    "nameFirst": "nameFirst",
    "personAvatar": "personAvatar",
    "jobTitle": "personTitle",
    "nickName": "personNickname",
    "_repeat": 9
  }
});

// Create a variable that stores the XMLHttpRequest object
var request = new XMLHttpRequest();

// Initialize the request – specify that the request is a POST and add the URL endpoint
request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");

// Send the request along with the payload
request.send(data);

request.onload = function(){
  // Access the JSON response generated from the request
  var fakeData = JSON.parse(this.response);
  console.log(fakeData);
}
					              
				            

Recap. We’ve successfully made a HTTP POST request containing data payload to the FakeJSON API endpoint, which returned us fake data as specified in JSON format.

Render JSON as HTML

This section involves using the data we’ve retrieved and displaying it as a web page. This is where the index.html file comes into play. We’ll be selecting and displaying things as HTML through the <div id=”root> element.

We’ll be accessing the <div id=”root> using getElementByID() in the scripts.js file. This method allows us to quickly access a uniquely named element on the page. We’ll then create a div element, containing a class attribute with the value of “container” using the setAttribute() method. Once that is done, we can now add the div class “container” to the div id “root” using the appendChild() method.

					              
var app = document.getElementById('root');

var container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);
					              
				            

Now that we’ve established the link between the index.html file and the scripts.js file, it’s time to move on to creating and populating the cards to be displayed. We’ll do this by using the code block that was part of the if statement we created earlier. Instead of printing out successful messages using console.log, we’ll be creating a card using a combination of div, img, heading and paragraph elements.

					              
request.onload = function(){
  // Access the FakeJSON response. In JSON.
  var fakeData = JSON.parse(this.response);

  // Conduct status check. We're doing some stuff for valid requests and a customary message for an invalid request.
  if (request.status >= 200 && request.status < 400) {
    fakeData.forEach(companyRole => {
      // Create a div element with a class of "card"
      var card = document.createElement('div');
      card.setAttribute('class', 'card');

      // Create an img element, populating it using the fake avatar retrieved from FakeJSON
      var elem = document.createElement("img");
      elem.setAttribute("src", companyRole.personAvatar);
      elem.setAttribute("height", "180px");
      elem.setAttribute("width", "100%");
      elem.setAttribute("alt", "Profile Picture");

      // Create a h1 element, populating it using the fake first name retrieved from FakeJSON
      var h1 = document.createElement('h1');
      h1.textContent = companyRole.nameFirst;

      // Create a p element, populating it using the fake job title retrieved from FakeJSON
      var p1 = document.createElement('p1');
      p1.textContent = companyRole.jobTitle;

      // Create a p element, populating it using the fake nickname retrieved from FakeJSON
      var p2 = document.createElement('p2');
      p2.textContent = 'Also known as "' + companyRole.nickName + '"';

      // Create a line break element, to separate the two p elements
      var br = document.createElement("br");

      // Append the div class "card" element to the previously created div class "container" element
      container.appendChild(card);

      // Append the img, h1, and p elements previously created to the div class "card" element
      card.appendChild(elem);
      card.appendChild(h1);
      card.appendChild(p1);
      card.appendChild(br);
      card.appendChild(p2);
    });
  } else {
    console.log('You shall not pass');
  }
}
					              
				            

Here’s the full scripts.js file containing all the JavaScript code we wrote including the condition for status code checking.

					              
var app = document.getElementById('root');

var container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);

var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
    "nameFirst": "nameFirst",
    "personAvatar": "personAvatar",
    "jobTitle": "personTitle",
    "nickName": "personNickname",
    "_repeat": 9
  }
});

var request = new XMLHttpRequest();

request.onload = function(){
  // Access the JSON response generated from the request
  var fakeData = JSON.parse(this.response);

  // Conduct status check. We're doing some stuff for valid requests and a customary message for an invalid request.
  if (request.status >= 200 && request.status < 400) {
    fakeData.forEach(companyRole => {
	  // Create a div element with a class of "card"
	  var card = document.createElement('div');
	  card.setAttribute('class', 'card');

	  // Create an img element, populating it using the fake avatar retrieved from FakeJSON
	  var elem = document.createElement("img");
	  elem.setAttribute("src", companyRole.personAvatar);
	  elem.setAttribute("height", "180px");
	  elem.setAttribute("width", "100%");
	  elem.setAttribute("alt", "Profile Picture");

	  // Create a h1 element, populating it using the fake first name retrieved from FakeJSON
	  var h1 = document.createElement('h1');
	  h1.textContent = companyRole.nameFirst;

	  // Create a p element, populating it using the fake job title retrieved from FakeJSON
	  var p1 = document.createElement('p1');
	  p1.textContent = companyRole.jobTitle;

	  // Create a p element, populating it using the fake nickname retrieved from FakeJSON
	  var p2 = document.createElement('p2');
	  p2.textContent = 'Also known as "' + companyRole.nickName + '"';

	  // Create a line break element, to separate the two p elements
	  var br = document.createElement("br");

	  // Append the div class "card" element to the previously created div class "container" element
	  container.appendChild(card);

	  // Append the img, h1, and p elements previously created to the div class "card" element
	  card.appendChild(elem);
	  card.appendChild(h1);
	  card.appendChild(p1);
	  card.appendChild(br);
	  card.appendChild(p2);
    });
  } else {
    console.log('You shall not pass');
  }
}

request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");
request.send(data);
					              
				            

Here’s the other full scripts.js file without the condition for status code checking.

					              
var app = document.getElementById('root');

var container = document.createElement('div');
container.setAttribute('class', 'container');

app.appendChild(container);

var data = JSON.stringify({
  "token": "59PxI89rzzVDP0m6B8PnWA",
  "data": {
    "nameFirst": "nameFirst",
    "personAvatar": "personAvatar",
    "jobTitle": "personTitle",
    "nickName": "personNickname",
    "_repeat": 9
  }
});

var request = new XMLHttpRequest();

request.onload = function(){
  // Access the JSON response generated from the request
  var fakeData = JSON.parse(this.response);

  fakeData.forEach(companyRole => {
	// Create a div element with a class of "card"
	var card = document.createElement('div');
	card.setAttribute('class', 'card');

	// Create an img element, populating it using the fake avatar retrieved from FakeJSON
	var elem = document.createElement("img");
	elem.setAttribute("src", companyRole.personAvatar);
	elem.setAttribute("height", "180px");
	elem.setAttribute("width", "100%");
	elem.setAttribute("alt", "Profile Picture");

	// Create a h1 element, populating it using the fake first name retrieved from FakeJSON
	var h1 = document.createElement('h1');
	h1.textContent = companyRole.nameFirst;

	// Create a p element, populating it using the fake job title retrieved from FakeJSON
	var p1 = document.createElement('p1');
	p1.textContent = companyRole.jobTitle;

	// Create a p element, populating it using the fake nickname retrieved from FakeJSON
	var p2 = document.createElement('p2');
	p2.textContent = 'Also known as "' + companyRole.nickName + '"';

	// Create a line break element, to separate the two p elements
	var br = document.createElement("br");

	// Append the div class "card" element to the previously created div class "container" element
	container.appendChild(card);

	// Append the img, h1, and p elements previously created to the div class "card" element
	card.appendChild(elem);
	card.appendChild(h1);
	card.appendChild(p1);
	card.appendChild(br);
	card.appendChild(p2);
  });
}

request.open("POST", "https://app.fakejson.com/q");
request.setRequestHeader("content-type", "application/json");
request.send(data);
					              
				            

Refresh the browser page containing the index.html. Voila, cards with the FakeJSON data.

Finished Tutorial Product with FakeJSON Data

Summary

You’ve successfully connected to the FakeJSON API using a POST request, specified the type of data response you’d like from the API URL endpoint and finally, displayed the data onto the screen. I hope this tutorial has been helpful to you in learning and using APIs as it has been to me researching and writing it.

Please feel free to share this article or let me know if you have any comments at jonathan@fakejson.com.

Sign up and start using our API now!

Get My API Token!