Using PokeAPI to build simple Pokemon Generator

anapi
5 min readDec 27, 2020

In this post I would like to share how I used The RESTful Pokémon API (https://pokeapi.co/) to create a simple Pokemon Generator, using static HTML5, CSS3, and, JavaScript.

View source code here: https://github.com/anapimolodec/pokemonia

So, let’s dive into the code step by step~

1. Think about what exactly you want to get from API.

p1. The data you can get from API (pokeapi.co)

It is really important to understand the information you can get using a selected API. In this case, PokeAPI provides tons of information about pokemon, and everything related~

So, I decided to retrieve some simple characteristics of a pokemon (such as name, image, physiology, and pokemon stats). If you are not familiar with the world of Pokemon (as I was in the beginning), you can read more about it on Bulbapedia.

2. Create an overall page layout with HTML and CSS.

p2. Page Layout

The top part had a simple Pokemon Symbol, Input Line, Enter, and Random Pokemon! buttons. You can search for a Pokemon by either entering a name or just ID (every pokemon has an ID in PokeAPI) or if you just want to get a random Pokemon, you can press the Random Pokemon! button.

The middle part is a placeholder where the pokemon will be shown. I used big fonts and simple design for better readability. And the lower part is just a footer with credentials.

P.S. you can style it in a much more fun and beautiful way. (check my CSS in source code)

3. Get (fetch) the needed data from API

In order to get data from the API, you select the preferred URL and use the following commands:

fetch(url)
.then( (raw_data) => raw_data.json())
.then( (data) => doSomething(data))
.catch((err) => {
console.log(err)})

You fetch (Promise in JS) the URL and get the raw data, then you transform it into JSON format so that JS can read the data and work with it. After that, you can use the readable data and apply your functions to it (like selecting the part that you need). In case of an error, you can catch the error and print it or any other message.

For example, you want to get the name of a Pokemon and add it into your HTML. To do so, select the place to put your results (like container/placeholder with class = “pokemon”) and get it using DOM.

const pokemon_html = document.querySelector('.pokemon')

Then, set a variable to a value you retrieved from the API using modern JS, such as:

const toAdd = `Name is : ${data.name}`

Then, you can use innerHMTL:

pokemon_html.innerHTML = toAdd

Simple as that!

In my case, I wanted to get several properties. Here is how I combined them:

const SearchPokemon = (api_obj) => {
//api_obj is an object, which parts makes up the URL
const {url, type, name} = api_obj //destructured object
const api_url = `${url}${type}/${name}` //URL string
fetch(api_url)
.then( (raw_data) => raw_data.json())
.then( (data) => changeHtml(data))
.catch((err) => { //if some error happens, it shows the following message
pokemon_html.innerHTML =
`<h1> Some Error Occured.. Please revise your code! </h1>`;
})
const changeHtml = (data) => {
let new_stats = []; //create an empty array where I will put stats
const get_stats = () => {
for (i=0; i< data.stats.length; i++) {
new_stats +=
[`<p> ${data.stats[i].stat.name} has base-stat of
<span class=”out”>${data.stats[i].base_stat}
</span> </p>`];}
return new_stats}
const got_stats = get_stats() //to have all stats as one variable///adding to HTML
const newHtml = `
<div class = “details” align=”center”>
<h1 class= “name” > ${data.name} </h1>
<img src= “${..img} “ />
<h3> weight: <span class=”out”>${data.weight} hg </span> </h3>
<h3> height: <span class=”out”>${data.height} dm</span> </h3>
<h3> type: <span class=”out”>${data.types[0].type.name} </span> </h3>
</div>
<div class= “stats”>
<h3>${data.name}’s stats: </h3>
${got_stats}
</div>`
pokemon_html.innerHTML = newHtml //add it into html
input.value = “”; //to reset the input line
}
}

P.S. See the source code for better code display

4. Make URL generation automatical by Input Value

To make the URL(where to fetch the data from) generation automatic, create the following function.

function MakeUrl(value) { //creates the URL using “value”
const api_obj = {
url: “https://pokeapi.co/api/v2/",
type: “pokemon”,
name: value,}
return api_obj;
}

The function above takes in a “value” which can be either ID or Pokemon name, typed into the Input Line or a random ID to get random pokemon. Also, you can try to use several “types” such as ability, type, etc. In my case, I limited it only to “pokemon”. It produces the object, which is used to form a URL string (as shown in part 3 above). You need this function if you want to implement the random pokemon generator because in such a case, “value” can be either form the input line or the random integer.

Then, we add Event Listeners to get the user-defined “value” and use it to generate URL, and correspondingly get data from the API.

5. Add dynamics with JS

This is my final JS code (which can also be found in the source code)

var btn = document.getElementsByTagName(“button”)[0];
var input = document.getElementById(“userinput”);
var rand_btn = document.getElementById(“random”);
const pokemon_html = document.querySelector(‘.pokemon’)
const SearchPokemon = (api_obj) => {
..shown in part 3 }
function MakeUrl(value) {
..shown in part 4 }
function inputLength() {
//checks if the input line input is not empty
return input.value.length;
}
function getRandomInt(min,max) {
//creates random integer
var rand_int= Math.floor(Math.random() * (max - min) + min);
console.log(rand_int);
return rand_int;
}
function Randomize(event) {
const search_value = getRandomInt(1,897);
//gets random integer between min and max of Pokemon IDs
SearchPokemon(MakeUrl(search_value));
//uses gotten integer as Pokemon ID and search
}
function SearchAfterClick(event) {
if (inputLength() > 0) {
SearchPokemon(MakeUrl(input.value));
//search Pokemon by using inputted value
}
}
function SearchAfterKeypress(event) {
if (inputLength()> 0 && event.keyCode === 13) {
//checks the Enter keyboard command
SearchPokemon(MakeUrl(input.value));
//search Pokemon by using inputted value
}
}

btn.addEventListener("click",SearchAfterClick);
input.addEventListener("keypress", SearchAfterKeypress);
rand_btn.addEventListener("click",Randomize);

Check the final website:

P.S. it is not designed for the mobile screen and can appear distorted. (but you can change the CSS and make it better~)

Thank you for reading this far! ❤

This is my very first post on Medium and I hope it is helpful to you!

Please check this video as it helped me a lot to build this.

--

--