Poke API

Author

Filip Kovac

Pokemon API

I accessed this api through https://pokeapi.co/.

Connecting to the API/Loading Library’s

library(tidyverse) 
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.2     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(jsonlite)  

Attaching package: 'jsonlite'

The following object is masked from 'package:purrr':

    flatten
library(magrittr)  

Attaching package: 'magrittr'

The following object is masked from 'package:purrr':

    set_names

The following object is masked from 'package:tidyr':

    extract
library(httr)
library(knitr)

base_url <- "https://pokeapi.co/api/v2/pokemon/"

Creating a vector of Pokemon for distinct URL’s & Making URL’s

By creating this vector you are able to input any pokemon of your choosing and it will created an accurate URL which is shown below.

pokemon_team <- c("mew", "pikachu", "squirtle", "treecko", "pidgey", "magikarp")
end <- "/?json=1"

poke_urls <- paste(base_url, pokemon_team, end, sep="") 

poke_urls[2]
[1] "https://pokeapi.co/api/v2/pokemon/pikachu/?json=1"

Creating a Function for the URL’s

all_data <- 
  function(url){
    data_raw <- 
      url %>% 
      GET() %>% 
      content(as = "text", 
              encoding = "UTF-8") %>% 
      fromJSON() 
      
    data <- 
      data_raw %>% 
      use_series(stats) %>% 
      mutate(pokemon = data_raw$name,
             stat = stat$name)
    
    return(data)
    
  }


all_data(poke_urls[2])
  base_stat effort            stat pokemon
1        35      0              hp pikachu
2        55      0          attack pikachu
3        40      0         defense pikachu
4        50      0  special-attack pikachu
5        50      0 special-defense pikachu
6        90      2           speed pikachu

Creating a loop

When creating this loop I was looking to get all the stats from the Pokemon on my team and add them to a data set.

poke_team <- data.frame()

for(i in seq_along(poke_urls)){
  poke_team <- 
    all_data(poke_urls[i]) %>% 
    bind_rows(poke_team)
  
  Sys.sleep(1)
  paste("Page",i,"of",length(poke_urls),"collected", sep = " ") %>% 
    print()
}
[1] "Page 1 of 6 collected"
[1] "Page 2 of 6 collected"
[1] "Page 3 of 6 collected"
[1] "Page 4 of 6 collected"
[1] "Page 5 of 6 collected"
[1] "Page 6 of 6 collected"
view(poke_team)

What this accomplishes

You are able to input any Pokemon you want when creating a team, it will output their stats like base stats, effort, and the name of the stat(attack, defense, hp, special attack/defense, and speed)