Need assistance with Javascript - API Integration. I have been trying to pull data off SWAPI (an open API) and fetch the data into our system. I am struggling with something now!
What I am trying to do is get the around 3 country names and get the people's attribute under that country. So fat I was able to get the country names using the following code:
(async () => {
let Name = [];
let Diameter = [];
let Resident = [];
for (i = 1; i < 4; i++) {
const PlanetDetails = await api.makeRequest({
method: 'GET',
url: `https://swapi.dev/api/planets/${[i]}`,
});
Name[i] = PlanetDetails.data.name;
Resident[i] = PlanetDetails.data.residents;
api.setVariable('Name1', Name[1]);
api.setVariable('Name2', Name[2]);
api.setVariable('Name3', Name[3]);
api.setVariable('R1', Resident[1]);
}
})();
But under the countries the residents' attributes are coming up as links like this:

I used POSTMAN here to test. When I click on the links I can see the person's attributes (e.g color, height, name, etc.). But How do I do that in JS?
Thank you
To get the resident's data, you need to make a request to the endpoint and then use the returned data. for example to get the data of the first resident, you can make a request to https://swapi.dev/api/people/1.
This code makes requests for each resident.
(async () => {
let Name = [];
let Diameter = [];
let Resident = [];
for (i = 1; i < 4; i++) {
const PlanetDetails = await api.makeRequest({
method: 'GET',
url: `https://swapi.dev/api/planets/${[i]}`,
});
Name[i] = PlanetDetails.data.name;
Resident[i] = await Promise.all(PlanetDetails.data.residents.map(async(resident) => {
let resident = await api.makeRequest({
method: 'GET',
url: resident,
});
console.log(resident.data); // for visually viewing the result.
return resident.data;
}));
api.setVariable('Name1', Name[1]);
api.setVariable('Name2', Name[2]);
api.setVariable('Name3', Name[3]);
api.setVariable('R1', Resident[1]);
}
})();