Assignment 6

The PokéAPI

The PokéAPI is a free REST API containing structured data on Pokémon. The data I’m focusing on is name, height, weight, and typing.

This API is useful for:

  • Learning how to use REST APIs in R

  • Practicing collection and transformation of data

  • Building datasets to analyze and visualize

  • Creating applications and gaining insights

Since The PokéAPI is free and doesn’t require authentication, it is an ideal API for beginners to start learning with

Loading In Library’s

  • library(tidyverse): Everything in Tidy

  • library(jsonlite): Conversion of JSON into Data Frames

  • library(magrittr): Piping and List Extraction

  • library(httr): Interacting with HTTP verbs

Setting Up the API

Since an API key is not needed, the base URL and the Pokémon name is all you need.

Below, I created a vector of Pokémon I was interested in gaining information about.

base_url <- "https://pokeapi.co/api/v2/" # Establishing a base URL

pokemon <- c("Pikachu", "Charizard", "Greninja") # list of Pokémon to collect information on

url <- paste(base_url, "pokemon/", pokemon, sep = "") # Building the full URL

Building a Function For Data Extraction

After creating the URLs for each Pokémon, we can use each URL as the input to a function for the following to occur:

  • Sends a GET request

  • Converts the response to text

  • Converts JSON -> Data Frame

pokemon_function <- function(url) {pokemon_data <- url %>%
  GET() %>%
  content(as = "text", encoding = "UTF-8") %>% 
  fromJSON()

type_names <- pokemon_data$types$type$name # Extracting type names

df <- data_frame(name = pokemon_data$name,
              height = pokemon_data$height,
              weight = pokemon_data$weight,
              types = paste(type_names, collapse = ", "))
    return(df)
}

Loop to Gather Results in Single Data Frame

pokemon_loop <- tibble()

for (i in seq_along(pokemon)) {pokemon_loop <- bind_rows(pokemon_loop, pokemon_function(url[i]))
Sys.sleep(3)
}
Warning: `data_frame()` was deprecated in tibble 1.1.0.
ℹ Please use `tibble()` instead.

Results

Below, we can see the output containing the name, height, weight and typing of the Pokemon.

pokemon_loop
# A tibble: 3 × 4
  name      height weight types       
  <chr>      <int>  <int> <chr>       
1 pikachu        4     60 electric    
2 charizard     17    905 fire, flying
3 greninja      15    400 water, dark