1 of 11

JS Fetch and API’s

For Web Dev 11

2 of 11

Review: JS Objects

Objects allow you to store different types of information within one variable.

// Create an object:

let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display the name and age in a webpage

let elem = document.getElementById("demo");

elem.innerHTML = person.firstName + " is " + person.age + " years old.";

​

3 of 11

JSON

JSON - Javascript Object Notation is a way of storing text data

It uses the same syntax as JavaScript Objects

Example:

{

"name" : "Jason",

"age" : "24",

"hometown" : "Missoula, MT",

"gender" : "male"

}

​

4 of 11

JSON Examples

Array of objects

[{

"name" : "Jason",

"age" : "16",

"grade" : "11"

},

{

"name" : "Kyle",

"age" : "17",

"grade" : "12"

}];

Nested JSON

{

"jason" : {

"name" : "Jason Lengstorf",

"age" : "24",

"gender" : "male"

},

"kyle" : {

"name" : "Kyle Lengstorf",

"age" : "21",

"gender" : "male"

}

}

​

5 of 11

Content API’s

  • There are a number of websites that provide content for other sites
  • They provide a variety of different interfaces to get and receive the data
  • Some of them are free
  • Rapid API https://rapidapi.com/collection/list-of-free-apis
  • We will learn to create websites that get content from API’s
  • We will only be using apis that:
    • Are free
    • Do not require a key
    • Work with JavaScript Fetch
    • Provide data in JSON

​

6 of 11

Activity API

The Activity API is a simple API that suggests activities for you to do.

https://mdinfotech.net/api/activity/

​

This is a sample response =>

​

​

{

"activity":"Write a poem",

"Type":"creative",

"Participants":1,

"Cost":"free"

}

​

7 of 11

How to Put API Content In Your Website

  1. Use the JS Fetch Command to request JSON data from an API
  2. Convert the data to a JavaScript Object
  3. Add the content to your website

​

8 of 11

URL for API

Assign html elements to global variables

Fetch data from url

Convert the JSON in the response to a JavaScript Object

data is the JS Object containing the data from the URL. Pass it to updateWebsite.

Print the data to the console so you can see what it looks like. Use this to figure out how to access the information.

Put the data you want in your website

Global variables

let typeDiv;

9 of 11

window.onload

Global variables

Allows you to execute code once the page has finished loading in the browser

​

​

Are visible to the whole script

Assign html elements to global vars after the page is finished loading.

​

​

​

window.onload = function() {

someVar = document.getElementById(“someid”);

} // window.onload

​

10 of 11

Async/await

When programming, you often need to handle tasks that take time, like fetching data, reading files, or waiting for a timer. These tasks are called asynchronous tasks because they don't block other parts of your program.

To manage asynchronous tasks more easily, use async and await.

async

  • added to a function declaration to indicate that it performs asynchronous operations.

await

  • used inside async functions to pause the function execution until a promise is resolved.

Error Handling: Use try...catch blocks to handle errors cleanly.

11 of 11

async/await

async function fetchContent() {

try {

// Send a GET request to the API

const response = await fetch(apiURL);

​

// Convert the response to JSON format

const data = await response.json();

​

console.log(data);

changeContent(data);

} catch (error) {

console.error('Error fetching activity:', error);

}

} // fetchContent

​