GDI Logo

Intermediate JavaScript

Class 4

Agenda

  • Review Quiz
  • Quiz App: last steps
  • Other APIs
  • Goodbye!😢

Review Quiz

⬇

What could be improved in the following code?


let students = ["Bob","Amy","Betty","Bill","Marge","Charlotte","Shawn","Pedro"];
let longestName = function(){
  let output = "";
  for(let i = 0; i < students.length; i++){
    let name = students[i];
    if(name.length > output.length){
      output = name;
    }
  }
  return output;
}
longestName();
            

// preference for const
const students = ["Bob","Amy","Betty","Bill","Marge","Charlotte","Shawn","Pedro"];
// Keep array reference within function as parameter (more versatile)
const longestStr = function(arr){
  let output = "";
  for(let i = 0; i < arr.length; i++){
    const str = arr[i];
    output = str.length > output.length ? str : output;
  }
  return output;
}
longestStr(students); // must pass data into fun  ction as argument
            

What is the value of pikachu.health?


const pikachu = {
  health: 10,
  defense: 5
}
const charmander = {
  punch: function(obj){
    const damage = 12 - obj.defense;
    obj.health -= damage;
  }
}
charmander.punch(pikachu);
            

pikachu.health; // (10 - (12 - 5)) == (10 - 7) == 3
            

How would you get all divs with a class of "xyz" from the DOM?


const divs = document.querySelectorAll("div.xyz");
            

Why does the following console.log() print "undefined?"


const URL = "https://some-api.com/api";
let info;
fetch(URL)
  .then(r=>r.json())
  .then(data=>{
    info = data;
  })
console.log(info); // undefined
            

The asynchronous fetch() call does not reassign the "info" variable before the console.log() executes

Events

An events is some notable moment for an element, such as when a user:

  • scrolls on the page
  • clicks an elements
  • presses a certain key


Check out all of the events that can occur on a website

Event Handlers

An event handler is a callback function that can be assigned to an element to trigger when an event occurs


const button = document.querySelector("button");
button.addEventListener("click",handleClick);
function handleClick(event){
  // event is an Event object with information about the event
  alert("Don't press me!");
}

Let's Develop It!

In the "mainProject" folder, go into "class_4", and edit the "script.js" file

  • Finish up last tasks!

const button = document.querySelector("button");
button.addEventListener("click",handleClick);
function handleClick(event){
  // event is an Event object with information about the event (check it out!)
  alert("Don't press me!");
}

The final product

This is what we made!

<br/>

Working with other APIs

Not all APIs are created equal - there are 3 main ways to access an API

  1. Open to all - no authentication required!
  2. Requires developer account and authentication key...
    1. which can be part of the request URL
    2. which must go in the request header

APIs open to all

Anyone can use these without needing permission or authentication!

  • 💲Free!💲
  • Usually has a low limit on the number of requests that can be made from the same IP address
  • A server is costly to maintain, and without proper backing many Open APIs shut down - making them less reliabile

APIs open to all - Example


const URL = "http://taco-randomizer.herokuapp.com/random/"; // TacoFancy API
fetch(URL)
  .then(response=>response.json())
  .then(console.log)

APIs with key in URL

  • Usually free!
  • Must sign up for a developer account - may include a small questionarre explaining your project
  • You will get an API key, which ensures API requests are coming from a legitimate source and not being abused
  • API key is passes along as a URL parameter
  • You may be asked to provide the domain from which requests will come from - this is another security measure
  • The request limit is usually NOT done by IP address - instead the number of requests per unit of time is limited (pay $$ to increase this limit)

APIs with key in URL - Example


const BASE_API = "https://api.nasa.gov/planetary/apod"; // NASA API

const API_KEY = "YOUR KEY HERE"; // get API key by signing up as a developer

const URL = BASE_API + "?api_key=" + API_KEY;
// "?api_key=" sets a URL parameter (can test this URL in browser directly!)
// parameter name is specified in the documentation

fetch(URL)
  .then(response=>response.json())
  .then(console.log)
  

Understanding a URL (with parameters)

APIs with key in request header

  • Usually free
  • Must sign up for a developer account
  • You will get an API key
  • API key passed through request header - an object that accompanies the request
  • May have to provide the domain from which requests will come from
  • Requests are limited by number per unit of time (pay $$ to increase this limit)

APIs with key in request header - Example


const URL = "https://favqs.com/api/qotd"; // Fav Quotes API

const API_KEY = "YOUR KEY HERE"; // get API key by signing up as a developer

const options = { // can have MANY more options
  method:"GET", // GETting response instead of POSTing one
  headers: {
    "Content-Type" : "application/json", // specifying JSON as returning data type
    "Authorization": "Token token=" + API_KEY // specified in documentation
  }
}

fetch(URL, options) // notice 2nd parameter!
  .then(response=>response.json())
  .then(data=>console.log(data.quote))
  

Reading Documentation

API Documentation is written by developers to help other developers understand how to use their API


Unfortunately, there is no standard for writing documentation and you will often bump into hard-to-read, outdated, and cryptic documentation

Tips for Reading Documentation

  • Get a sense of how the documentation is organized
  • Explore example code (copy & paste)
  • Try out the first 3 methods or topics that catch your eye
  • GOOGLE IT!

Let's Develop It!

Take 2 minutes to explore the Random User API Documentation

  • How would you request 100 random users?
  • How would you request 100 female random users?
  • How would you request a male from the US?
  • How would you request 10 random users with only their name and cell number?

Let's Develop It! - Answer


// 100 random users
"https://randomuser.me/api/?results=100"

// 100 female random users
"https://randomuser.me/api/?results=100&gender=female"

// a male from the US
"https://randomuser.me/api/?gender=male&nat=us"

// 10 random users with only their name and cell number
"https://randomuser.me/api/?results=10&inc=name,cell"

Nested API calls

A typical pattern you'll see is when the data from one API call provides the information or setup for another API call.


// Random User API
const URL_1 = "https://randomuser.me/api";

// Sunrise and Sunset times API
const URL_2_BASE = "https://api.sunrise-sunset.org/json?date=today";

fetch(URL_1)
  .then(response=>response.json())
  .then(userData=>{
    const name = userData.results[0].name;
    const full_name = `${name.first} ${name.last}`;

    const coordinates = userData.results[0].location.coordinates;
    const lat = coordinates.latitude;
    const long = coordinates.longitude;

    // Sunrise & Sunset API can accept URL parameters for longitude
    // and latitude to get the sunrise and sunset for that location
    const URL_2 = URL_2_BASE + "&lat=" + lat + "&lng=" + long;
    fetch(URL_2)
      .then(response=>response.json())
      .then(ss_data=>{
        const sunrise = ss_data.results.sunrise;
        const sunset = ss_data.results.sunset;
        console.log("My name is" + full_name);
        console.log("My sunrise was at " + sunrise);
        console.log("My sunset will occur at " + sunset);
      })
  })
        

Notice the 2nd fetch is WITHIN the first's callback

Take Home Assignment

Find 1 API we didn't use and create a web application allowing users to interact with it. For example:

  • Use the Pokemon API and allow users to search for pokemon by name
  • Use the Giphy API and allow users to find images by different criteria
  • Use the Google Maps API to send users on treasure hunts based on location


The possiblities are endless!

Additional Resources

So Long! Farewell!

Wrapping Up

  • Complete Surveys!