library(tidyverse) # All the tidy things
library(jsonlite) # Converting json data into data frames
library(magrittr) # Extracting items from list objects using piping grammar
library(httr) # Interacting with HTTP verbsAssignment 6: Pokemon API
The PokeAPI
The PokeAPI is a free, open-access API that provides structured data about Pokémon. This includes information such as a Pokémon’s name, height, weight, abilities, and base experience.
This API is useful for:
Learning how to work with REST APIs in R
Practicing data collection and transformation
Building datasets for analysis or visualization
Creating applications related to Pokémon data
Because it is completely free and does not require authentication, it is ideal for beginners learning how APIs work.
Setting Up the API
Load in all packages
Use the Base URL Provided to Call on the API
Since no API key is needed the base url and the Pokemon you want information about is all you need to add onto the base url.
Additionally, I created a vector of pokemon that I wanted information about in this step as well.
#establishes a base url to be used
pokemon_base_url <- "https://pokeapi.co/api/v2/"
#list of pokemon to collect information for
pokemon_name <- c("pikachu", "piplup", "bulbasaur")
#building full URL
url <- paste(pokemon_base_url, "pokemon/", pokemon_name, sep = "")Building Function to Extract Data
After creating the urls for each Pokemon in the previous step, we can use the url as the input in a function that will get all of the information from each link and return a data frame containing the data from each url.
pokemon_function <-
function(url) {
pokemon_data <-
url %>%
GET() %>%
content(as = "text",
encoding = "UTF-8") %>%
fromJSON()
df <- data_frame(
name = pokemon_data$name,
height = pokemon_data$height,
weight = pokemon_data$weight,
base_experience = pokemon_data$base_experience
)
return(df)
}Loop to Gather Results in one Data Frame
Finally, in order to gather results from each Pokemon, we will loop through each url that was created and bind the output to the pokemon_df.
pokemon_df <- tibble()
for (i in seq_along(pokemon_name)) {
pokemon_df <-
bind_rows(pokemon_df, pokemon_function(url[i]))
Sys.sleep(3)
}Results
Here we can see the output containing the names of the Pokemon and the attributes associated with them.
pokemon_df# A tibble: 3 × 4
name height weight base_experience
<chr> <int> <int> <int>
1 pikachu 4 60 112
2 piplup 4 52 63
3 bulbasaur 7 69 64