For this assignment I will be using PokeAPI, a free and open database of Pokemon game data. It covers every Pokemon, along with moves, abilities, berries, and each generation that has been released, and it is available at https://pokeapi.co/.
In this tutorial I will show how to set up and call the API, then use it to find the top 25 Pokemon ranked by base experience. Base experience is the number of experience points a player receives for defeating that Pokemon.
PokeAPI does not require an account or an API key, so there is nothing to sign up for.
First we’ll load the packages into the script.
library(tidyverse)
library(jsonlite)
library(httr)
I’ll also establish an endpoint here.
endpoint <- "https://pokeapi.co/api/v2/pokemon/"
With the endpoint established we can build the function that makes the call to the API. It will combine the endpoint and other necessary variables into the url.
get_url <- function(id) {
poke_url <- paste(endpoint, id, sep = "")
poke_API <-
poke_url %>%
GET()
pokemon <-
poke_API %>%
content(as = "text",
encoding = "UTF-8") %>%
fromJSON()
pokemon_info <- data.frame(
PokeID = pokemon$id,
Name = pokemon$name,
Base_Experience = pokemon$base_experience %||% NA)
return(pokemon_info)
}
Now we can make the calls to the API. This will make 1025 calls to cover every Pokemon in the Pokedex and will output a data set that can be combed through to extract the top 25 Pokemon with most base experience.
last_id <- 1025
all_pokemon <- map(1:last_id, function(id) {
Sys.sleep(0.3)
get_url(id)
}) %>%
bind_rows()
write_csv(all_pokemon, "pokemon_xp.csv")
Finally, here we pull out the 25 Pokémon with the highest base experience and save them to their own file.
top25 <- all_pokemon %>%
slice_max(Base_Experience, n = 25, with_ties = FALSE)
write_csv(top25, "top25_base_experience.csv")
The saved file can now be loaded like any other data set, with no API call needed.
top25 <- read_csv("top25_base_experience.csv")
top25
## # A tibble: 25 × 3
## PokeID Name Base_Experience
## <dbl> <chr> <dbl>
## 1 242 blissey 608
## 2 113 chansey 395
## 3 531 audino 390
## 4 890 eternatus 345
## 5 888 zacian 335
## 6 889 zamazenta 335
## 7 1007 koraidon 335
## 8 1008 miraidon 335
## 9 493 arceus 324
## 10 150 mewtwo 306
## # ℹ 15 more rows