Skip to content

9.2 JSON Data and APIs

Overview
An introduction to JSON data, dynamic websites, and APIs.
Excerpt Section 9.2.1

A Javascript object is a hierarchical format for storing collections of properties. While an array stores a list of values identified by their index, object properties store values using a name (also referred to as a key).

let color = {
id: "cyan",
hex: "00ffff",
};

See the Pen Javascript Objects by Owen Mundy (@owenmundy) on CodePen.

Explore this full tutorial https://criticalwebdesign.github.io#js-objects

JSON (Javascript Object Notation) is essentially the same structure, with some small differences, but it can be stored in a separate file and sent over a network.

colors.json
[
{ "id": "cyan", "hex": "00ffff", "rgb": [0, 255, 255] },
{ "id": "magenta", "hex": "ff00ff", "rgb": [255, 0, 255] },
{ "id": "yellow", "hex": "ffff00", "rgb": [255, 255, 0] },
{ "id": "black", "hex": "000000", "rgb": [0, 0, 0] }
]
Excerpt
Section 9.2.3

In this exercise you’ll learn to test APIs. There are hundreds of free APIs that offer a wealth of functionality and data for you to use in your projects. Some APIs require you to register and send requests along with a special key to prevent abuse, but there are plenty of public APIs you can use as well.

  1. We will use this free API that offers facts about cats. You should always refer to an API’s documentation, in this case catfact.ninja, to learn about the endpoints, or specific URLs used to access particular information. Open the following link in a web browser and you should see a simple JSON document, organized by key:value relationships: catfact.ninja/fact
  2. Install the JSON Formatter extension for Chrome criticalwebdesign.github.io#json-formatter to make it easier to read JSON data in the browser, and reload the cat fact API.

JSON A cat fact in JSON formatted with JSON Formatter. Fascinating.

  1. [object JSON] Placeholder is a free “realistic” API for testing. For example, access the “users” endpoint to get a list of fake users: jsonplaceholder.typicode.com/users
  2. While basic API testing can be as simple as viewing a web page, sometimes you may need special tools to send data or authenticate. For the next API we’ll use a tool called REQBIN to send information with the API request that lets you mimic a web form’s POST request. The “Real REST API” restful-api.dev we will use features endpoints that operate differently, depending on the HTTP verb you use in the request. Go to reqbin.com and add the following URL in the field—watch out for errant spaces at the end of the URL. Send the request with GET selected in the dropdown and you’ll see a list of devices.

https://api.restful-api.dev/objects

New Material
Test an API using the POST method and a remote database.
  1. While still on reqbin.com (continuing from the above activity) with the previous URL still in the path field https://api.restful-api.dev/objects
  2. Change the dropdown to POST, and then under content tab type or paste the following JSON data. Feel free to change the value of any property. Press Send and your data will be sent to the API and then returned with an additional id property. Copy the value of the id.
{
"name": "Owen's Computer",
"data": {
"year": 2024,
"color": "Sparkleberry"
}
}
  1. Open a new browser tab and add the id you copied to the end of the following URL after the equal sign and press return. You should see the data you sent with the first request. Here is the one we sent: criticalwebdesign.github.io#restful-api.
https://api.restful-api.dev/objects?id=

Screenshot of POST results include an id. Using the POST method we added an entry to the dataset by following the JSON formatting rules to specify keys and values. In the result, our entry includes a new key for id.

Excerpt Section 9.3.1
Any time you load data over a network you incur latency, a delay between when you make your request and the moment the response arrives. With zero latency web pages feel speedy and the instant response is gratifying, while lag between user events can make a website clunky and frustrating.

Charts showing synchronous vs. asynchronous wait times in bright hues on a black background. The performance benefits from using asynchronous code are visible on these side-by-side charts.

Chart showing the concept of a promise chain in planning a meet-up to ride bikes. The work day is almost over and you want to go ride bikes with your friends. You reach out to see who is available (three requests) and wait for a response. Of the three you ask, Sam cannot ride (promise rejected), Letícia can go at 3:45pm, and Angel can meet at 4:30pm (two promises pending). You do other work while you wait, perhaps finishing the section of a chapter you are writing, and then head out to meet each friend who resolves their promise by arriving at the trailhead.

See the Pen Asynchronous Javascript by Owen Mundy (@owenmundy) on CodePen.

See this Codepen https://criticalwebdesign.github.io/#async-js

Paris Tim Schwartz created Paris by writing a data scraper that monitored news and search engines for “paris hilton” and “paris france” and displayed the results in real time.

New Material
Any time you load data over a network you incur latency, a delay between when you make your request and the moment the response arrives. With zero latency web pages feel speedy and the instant response is gratifying, while lag between user events can make a website clunky and frustrating.

Objects are commonly used to represent the properties and behaviors of entities in a programming model called Object Oriented Programming (OOP). OOP languages use predefined classes and inheritance to derive behavior. For example, all objects of a car class will have wheels and headlights that turn on, which are inherited by its child classes that define more specific properties.

Javascript uses a(n arguably simpler) prototype pattern to define objects. When you create a new variable in Javascript it creates a new copy of the object prototype, cloning all its functionality and data. Javascript’s prototype shares many of the OOP’s benefits. For example, Javascript objects use encapsulation to group and identify similar information inside a single container (like formats for a color), and standardizes access to their properties.

Type an open and close curly brace in the DevTools Console to see the properties all objects receive from the prototype:

{}
// -> [[Prototype]]: Object
constructor: ƒ Date()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
...

In the console, create a new object:

let color = {
name: "red",
}

If you log the color value you can see the name property you creaded, as well as the constructor from the prototype:

color
// -> {name: "red"}
[[Prototype]]: Object
constructor: ƒ Date()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
...

If you type the constructor (the method in each object that creates itself) of any data type based on the object, like Date, you will again see the prototype functions listed below the functions (ƒ) specific to that object.

new Date()
// -> constructor: ƒ Date()
getDate: ƒ getDate()
getDay: ƒ getDay()
getFullYear: ƒ getFullYear()
...
[[Prototype]]: Object
constructor: ƒ Date()
...