Skip to content

Instantly share code, notes, and snippets.

@MikeyBeLike
Last active August 2, 2023 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeyBeLike/6e43dc7b074eb84733cb59aae9fb4958 to your computer and use it in GitHub Desktop.
Save MikeyBeLike/6e43dc7b074eb84733cb59aae9fb4958 to your computer and use it in GitHub Desktop.
Normalise Pokemon API Data
import {
promises as fs
} from 'fs'
import fetch from 'node-fetch'
const POKEMON_API_BASE_URL = 'https://pokeapi.co/api/v2'
function extractPokemonIdFromUrl(url) {
return new URL(url).pathname.split('/').at(-2) ?? ''
}
async function fetchAllPokemon() {
let url = `${POKEMON_API_BASE_URL}/pokemon?limit=2000`
const response = await fetch(url)
const data = await response.json()
let pokemonData = data.results;
// Fetch detailed data for each Pokémon
for (let i = 0; i < pokemonData.length; i++) {
const pokemon = pokemonData[i]
const pokemonResponse = await fetch(pokemon.url)
const pokemonDetailedData = await pokemonResponse.json()
// Fetch species data for each Pokémon to get the color and habitat
const speciesResponse = await fetch(pokemonDetailedData.species.url)
const speciesData = await speciesResponse.json()
// Include only the attributes we're interested in
pokemonData[i] = {
id: pokemonDetailedData.id,
name: pokemon.name,
weight: pokemonDetailedData.weight,
height: pokemonDetailedData.height,
image: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${pokemonDetailedData.id}.png`,
color: speciesData.color ? {
id: Number(speciesData.color.url.split("/")[6]),
name: speciesData.color.name
} : null,
habitat: speciesData.habitat ? {
id: Number(extractPokemonIdFromUrl(speciesData.habitat.url)),
name: speciesData.habitat.name
} : null,
types: pokemonDetailedData.types.map(type => ({
id: Number(extractPokemonIdFromUrl(type.type.url)),
name: type.type.name
}))
}
}
return pokemonData
}
fetchAllPokemon()
.then(data => {
fs.writeFile('pokemon_data.json', JSON.stringify(data, null, 2))
.then(() => console.log('Pokemon data saved to pokemon_data.json'))
.catch(err => console.error('Error writing file:', err))
})
.catch(error => console.error('An error occurred:', error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment