JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  • JavaScript Time
  • Fetch
  • After the Fetch
  • Dealing with the Response
  • Using the Data
  • Getting Results to the HTML
  • Creating List Items
  • Putting Text in Our List Items
  • Adding the List Items to the List
  • Let's See It in Action
  • Further Practice
  1. 03-API Fundamentals
  2. 3-Fetch
  3. Star Wars

Star Wars JS

JavaScript Time

Now we get to actually use fetch and our Star Wars API! Open your HTML file in your browser, and refresh it every time we make a change to our JS file to see what happens. Keep your console open in your terminal! The first thing we need to do is be able to put information in the <ul> from our HTML. Recall what we talked previously about querySelectors. We're going to use that now to be able to use that in JavaScript. Type the following code in your star-wars-scripts.js file.

var starWarsPeopleList = document.querySelector('ul');

Next, we need to somehow GET information from our Star Wars API, and then format it to be displayed on our HTML page. Let's start with the GET.

Fetch

Remember what we talked about in fetch? It's time to put that knowledge to use. Let's start a fetch the API endpoint that we want to use. Our star-wars-scripts.js should look like the following. This fetch is going to go GET information from the Star Wars API people endpoint. Since we didn't specify a method, it will perform a GET request to the people endpoint of the API.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people')

After the Fetch

Now that we've done our fetch, how do we actually get the information back from it? Since fetch starts a Promise, we can use the then() method to return that Promise. As a reminder, then() takes up to two arguments: callback functions for the success and failure cases of the Promise. Here, we're just using the success argument and calling it response. If successful, we'll get a response back from the API, and then we can do stuff with it!

Make your star-wars-scripts.js look like this.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) { 

})

Dealing with the Response

So, now that we have captured our response, we need it in a format where we can use it! Right now, let's console.log our response.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) { 
console.log(response)
})
var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {

});

Using the Data

Now that we've gotten our information back and used .json() on it, let's take a look at it. Put the following console .log in.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  console.log(json)
});

You should see an object with some properties like count, next, previous, and results. The results is an array of 10 objects, and if you open it, you can see that this contains our people information!!! We can capture that information in a variable.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  let people = json.results;
});

Getting Results to the HTML

We know that our people is an array of objects. Think back to learning about loops (for...of versus for...in). Recall that for...of lets us iterate over values in an array, while for...in will print out the properties. Let's console.log both of these to decide which to use to handle our data.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  let people = json.results; 

  for(p of people) {
    console.log(p);
  }

  for(p in people){
    console.log(p);
  }

});

Creating List Items

Notice how the for...of prints the objects in our console.log, while for...in just prints numbers? That's because for...in is only grabbing the property, which in an array is the index, so we see 0-9. Now, we know that we need to use for...of going forward. We'll start by deleting our for...in, and then work with our for...of. In this loop, we are going to create the elements we need to display to the front end. Since we have a ul in our HTML, we need to create lis of all of our data.

We can create these list items in JS by using document.createElement(), which takes a parameter of the tag to create. So in our instance we're going to create lis.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  let people = json.results; 

  for(p of people) {
    let listItem = document.createElement('li'); 
  }

});

Putting Text in Our List Items

Now we're going to create a list item for every object we have in our array. Then, we need to put some text in our list item from our API. How can we change the stuff inside of a HTML tag without manually writing it? Fortunately, there is a method we can use called .innerHTML(). This method can be used to grab the value of the inner HTML or set it if we provide a parameter. In this case, we're going to set the inner HTML value. We're specifically going to put a <p> tag with the name inside. So in our for...of loop we're referring to each object as p to allow us access to the name via p.name. Type on the code below to make your star-wars-scripts.js file look like this:

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  let people = json.results; 

  for(p of people) {
    let listItem = document.createElement('li'); 
    listItem.innerHTML = '<p>' + p.name + '</p>';  
  }

});

Adding the List Items to the List

Now that we have our list item with the name inside of it, we just need to place all of these list items inside of the unordered list. We have a variable for that unordered list already, called starWarsPeopleList, and we can just use the .appendChild() method, which (from MDN) "adds a node to the end of the list of children of a specified parent node". To accomplish this, we're going to add a child of our list item to our parent unordered list.

var starWarsPeopleList = document.querySelector('ul');

fetch('https://swapi.co/api/people') 
.then(function(response) {   
  return response.json(); 
})
.then(function(json) {
  let people = json.results; 

  for(p of people) {
    let listItem = document.createElement('li'); 
    listItem.innerHTML = '<p>' + p.name + '</p>'; 
    starWarsPeopleList.appendChild(listItem);  
  }

});

Let's See It in Action

When you refresh your HTML page, you should see some people names from our Star Wars API!!! It didn't take us too many lines of code to be able to make a request to the Star Wars API, turn that response into something we can use, and display information in our HTML!

Further Practice

Play with a different endpoint of the Star Wars API! Try using planets, ships, or whatever else you want. Try to follow the same pattern.

PreviousStar Wars SetupNextRandom Photo

Last updated 7 years ago

You should see a bunch of information, including a body with some more stuff that we can't see. We need to be able to access that information! To do that we can use .json(). From the MDN docs: ".json() method of the Body takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON." (For more information on mixins, see the above link.) So what does this mean? Basically, it means it reads the body so we can use it and returns a promise once it's done parsing the body as JSON. Now, we can call .json() on the response, and then use another .then() after the Promise resolves, so we can use the json we get back!

mixin