Go Back to Home
image featured post
React JS

Learn how to use the RESTful Pokémon API to create new websites

  • Rui Vergani Neto
  • 27, August, 2022
  • 3 min read
Search through topics

Introduction

This project will be dedicated to the practice of everything learned in the Javascript module at the CodeBoost course. In addition to the well-crafted layout, the project itself will be based on API queries to bring up the information that the user interacts with.

New features Learned

  • Creating detailed Modal
  • The search input area is fully functional
  • Using API to get all pokemon data
  • Implementing a load more button
  • Learning about Axios, JSON, and HTTP requests.

Using RESTful API with Axios

Axios is a client HTTP based on promises for node.js and the browser. One of the many advantages of using Axios is that there is no need to convert the data to JSON because will be automatically converted.

Some of the JavaScript functions created were basically done to get the data from the API and others to generate the HTML code in JS, for example, the cards, all of them if you want to manage in a dynamic way getting the data from API you need to think about listing these cards in a dynamic way as well.

What I recommend you do is create a function to create this card in JS (using your HTML reference) and then create another function to list the data from the API, once you have this data you can implement it into the Card.

Use the following code to create a card using JS

// CREATE CARD POKEMON (JS)
function createCardPokemon(code, type, nome, imagePok) {
    // Card Element
    let card = document.createElement('button');
    card.classList = `card-pokemon js-open-details-pokemon ${type}`;
    card.setAttribute('code-pokemon', code); // attribute for pokemon code (link to the modal)
    areaPokemonsList.appendChild(card); // append all cards

    // Div Image
    let image = document.createElement('div'); // create any html element
    image.classList = 'image'; // add class image 
    card.appendChild(image); // put in the card (button element)

    let imageSrc = document.createElement('img');
    imageSrc.setAttribute('src', imagePok); // set attribute to imagePok (parameter)
    imageSrc.className = 'thumb-img';
    image.appendChild(imageSrc);

    // Div Info
    let info = document.createElement('div');
    info.classList = 'info';
    card.appendChild(info);

    // Div Text
    let text = document.createElement('div');
    text.classList = 'text';
    info.appendChild(text);

    let codeSpan = document.createElement('span');
    codeSpan.textContent = (code < 10) ? `#00${code}` : (code < 100) ? `#0${code}` : `#${code}`; // condition to show #001 or #010 or #100
    text.appendChild(codeSpan);

    let pokemonName = document.createElement('h3');
    pokemonName.innerText = `${capitalizeFirstLetter(nome)}`; // capital letter uppercase
    text.appendChild(pokemonName);

    // Div Icon
    let icon = document.createElement('div');
    icon.classList = 'icon';
    info.appendChild(icon);

    let typeImg = document.createElement('img');
    typeImg.setAttribute('src', `img/icon-types/${type}.svg`); // does not exist in the API so we create same image name as the types to run through our images
    icon.appendChild(typeImg);
}

Have a look below at the function to list all pokemon using RestfulAPI

// LIST THE POKEMONS
function listingPokemons(urlApi) { // url from API
    // 1 - Get all pokemons from the API (0 - 9)
    // 2 - Pass results, next, count as parameter
    // 3 - Go through the each pokemon API (array) to get the details from each pokemon
        axios({
            method: 'GET',
            url: urlApi
        })
        .then((response) => { // succeed response will do the below config: 
            // all variables:
            const countPokemons = document.getElementById('js-count-pokemons');
            // results = all pokemons
            // count = sum of all pokemons
            // next = next pagination of pokemons (0 - 9)
            const { results, next, count } = response.data; // simple way of running through the OBJECT instead of using always response.data.results
            countPokemons.innerText = count; // innerText = count (all pokemons in the API)

            // Array of results (pokemons)
            results.forEach(pokemon => {
                let urlApiDetails = pokemon.url; // get URL from each pokemon
                axios({
                        method: 'GET',
                        url: `${urlApiDetails}` //string
                    })
                    .then((response) => {
                        const { name, id, sprites, types } = response.data;
                        // name = nome pokemon
                        // id = id pokemon
                        // sprites = image of pokemon
                        // types = tipo do pokemon

                        // Object to get only information I need
                        const infoCard = {
                            nome: name,
                            code: id,
                            image: sprites.other.dream_world.front_default, // path of the image
                            type: types[0].type.name // always first position
                        }
                        createCardPokemon(infoCard.code, infoCard.type, infoCard.nome, infoCard.image); // ** CALLING FUNCTION
                        
                        // select all pokemons to open modal
                        const cardPokemon = document.querySelectorAll('.js-open-details-pokemon'); // class
                        cardPokemon.forEach(card => {
                            card.addEventListener('click', openDetailsPokemon);
                        })
                    })
            })
        })
}

// load page => load function
listingPokemons('https://pokeapi.co/api/v2/pokemon?limit=9&offset=0'); // ** CALLING FUNCTION 

Process of development

Basically, following the Figma layout, I created all components, modal, and responsive parts of the website using static data without connecting it to the pokeAPI. Later on, I linked the API to make the website dynamic and learn how to use a RESTful API.

The following steps were taken:

  • Initial configuration
  • Exporting all assets
  • Creating components (HTML and CSS only)
  • Variables of colors
  • Modal of details pokemon (Static)
  • Header
  • Section slide hero
  • Section filtering and listing all pokemon types (Static)
  • Listing all Pokemons in JS and RestfulAPI
  • Listing all types of Pokemons in JS and RestfulAPI
  • Functionality – Load More in JS and RestfulAPI
  • Filtering all Pokemons per page in JS and RestfulAPI
  • Search feature for Pokemons in JS and RestfulAPI
  • Responsive for all components

Check the resources

🌍 Check the Project online: https://ruivergani.github.io/lp-pokemon/

🌍 SASS Library: https://sass-lang.com/

🌍 PokeAPI: https://pokeapi.co/

🌍 SEO Metatags: https://metatags.io/

🌍 AOS Animate: AOS Animate

🌍 Swiper Slide JS: https://swiperjs.com/

Contact me

  1. * Website developed in 2022 for learning and training purposes, by Rui Vergani Neto

Similar Articles

Check similiar articles below 🚀