leopolis
leopolis

Reputation: 23

How to get data from the links in an API?

I need to get some data from this API-page: https://swapi.dev/api/films/2. Specifically, I need to get the name, gender, and date of birth of each character from the second episode of Star Wars.

Without problems I can get the main data of the film, such as the title, the director, the producer and so on. However, I cannot get the data of the individual characters.

I tried to do this with just one function and thought it would be useful to create a for loop. The loop should fetch each result and then return the searched data to me.

async function GetCharacters() {
  const people = fetch("https://swapi.dev/api/films/2/").then(data => {
    return data.json();
  }).then(films => {
    console.log(films.characters)
  })

  for (let i = 0; i < people.length; i++) {
    const request = await fetch(film.characters[i]);
    const character = await request.json();
    console.log(character.name)
    console.log(character.gender)
    console.log(character.birth_year)
  }
}

GetCharacters()

However, the result I get is different from what I would like:

['https://swapi.dev/api/people/1/', 'https://swapi.dev/api/people/2/', 'https://swapi.dev/api/people/3/', 'https://swapi.dev/api/people/4/', 'https://swapi.dev/api/people/5/', 'https://swapi.dev/api/people/10/', 'https://swapi.dev/api/people/13/', 'https://swapi.dev/api/people/14/', 'https://swapi.dev/api/people/18/', 'https://swapi.dev/api/people/20/', 'https://swapi.dev/api/people/21/', 'https://swapi.dev/api/people/22/', 'https://swapi.dev/api/people/23/', 'https://swapi.dev/api/people/24/', 'https://swapi.dev/api/people/25/', 'https://swapi.dev/api/people/26/']

Instead of getting the searched data for each character, I get an array of links, as if the loop didn't work. Why is that?

Upvotes: 2

Views: 483

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

There's two issues here. Firstly, the people variable holds a Promise object, not the data returned from the AJAX request. Therefore your for loop is not executing. You need to perform the loop through the characters array within the callback.

Secondly, you're using await in the arrow function which is not async. To fix this you can use the same fetch().then() pattern within the loop to retrieve character information:

function GetCharacters() {
  fetch("https://swapi.dev/api/films/2/").then(d => d.json()).then(films => {
    films.characters.forEach(url => {
      fetch(url).then(d => d.json()).then(character => {
        console.log(character.name, character.gender, character.birth_year);
        // work with the character data here...
      })
    })
  })
}

GetCharacters()

Upvotes: 3

Related Questions