R
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Data Structures
-
Section 4: Data Manipulation
-
Section 5: Visualization and Statistics
-
Section 6: Advanced R
-
Section 7: Practical Projects
-
Section 8: Interview Practice
-
Section 9: More Practice Exercises
-
Section 10: Shiny Apps in Depth
-
Section 11: More Data Wrangling
-
Section 12: Tidyverse Deep Dive
-
Section 13: Statistical Modeling Deep Dive
-
Section 14: Machine Learning in R
-
Section 15: R Visualization Deep Dive
-
Section 16: R Package Development Deep Dive
-
Section 17: R for Reproducible Research
-
Section 18: R and Databases
-
Section 19: R Performance Optimization
-
Section 20: Bioinformatics and Specialized R
-
Section 21: More Shiny Practice
-
Section 22: More Practice Exercises
-
Section 23: R Data Structures Deep Dive
-
Section 24: More Interview and Review
-
Section 25: R for Business Analytics
-
Section 26: R Text Mining and NLP
-
Section 27: R Spatial Data Analysis
-
Section 28: R Deep Learning
-
Section 29: Advanced Statistical Techniques
-
Section 30: R Object Systems Deep Dive
-
Section 31: R Environments and Metaprogramming
-
Section 32: R for Finance
-
Section 33: R for Clinical and Health Data
-
Section 34: More Shiny Advanced Practice
-
Section 35: R Data Cleaning Deep Dive
-
Section 36: R Reporting Automation
-
Section 37: More Practical Projects Round 2
-
Section 38: R Ecosystem and Career
-
Section 39: More Visualization Practice
-
Section 40: R for Experimentation
-
Section 41: R for Genomics and Bioinformatics Deep Dive
-
Section 42: R for Marketing Analytics
-
Section 43: R Data Import/Export Deep Dive
-
Section 44: R String Processing Deep Dive
-
Section 45: R for Actuarial and Insurance Analytics
-
Section 46: R Testing and Quality Assurance Deep Dive
-
Section 47: R Version Control and Collaboration
-
Section 48: R Advanced Functional Programming
-
Section 49: R for Supply Chain and Operations
-
Section 50: More Practice Exercises Round 3
-
Section 51: R Dashboards and BI Integration
-
Section 52: R Data Governance and Ethics
-
Section 53: More Modeling Practice
-
Section 54: R Final Capstone Projects
-
Section 55: R for Sports Analytics
-
Section 56: More Interview Practice Round 2
-
Section 57: R Networking and APIs
-
Section 58: R for Environmental Science
-
Section 59: R Notebook and Documentation Practices
-
Section 60: More Data Wrangling Mastery
-
Section 61: R for A/B Testing at Scale
-
Section 62: R Package Ecosystem Deep Dive
227: Consuming REST APIs from R with httr2
If you've spent any time in R, you've probably used jsonlite to read a file, but interacting with a live web service is a different beast. We used to rely heavily on httr, but httr2 is the modern successor. It’s designed around a "request-perform" pipeline that feels much more like how we actually think about HTTP calls.
I want to grab some data from the PokéAPI—it's a free, no-auth API that's perfect for testing. Let's see if we can get the details for Pikachu.
Just trying to get a signal
My first instinct is to just "call" the URL. Let's see what happens when I set up a basic request.
library(httr2)
req <- request("https://pokeapi.co/api/v2/pokemon/pikachu")
print(req)
If you run that, you'll notice something weird: nothing actually happened. No data was downloaded. That's because request() doesn't actually make the request; it just creates a "request object." It's like writing a letter and putting it in an envelope, but you haven't walked to the mailbox yet. This is actually great because it lets us modify the request (adding headers, auth, etc.) before we actually send it over the wire.
To actually trigger the network call, I need req_perform().
resp <- req |> req_perform()
print(resp)
Now we have something. But look at the output. It's a wall of HTTP headers: Status 200, Content-Type, Date, Server. This is the "envelope" coming back to us. I don't care about the server version; I want the Pokémon data.
Digging into the JSON
The response object resp contains the body, but it's usually in raw bytes. I need to tell R to parse that raw data into something usable, like a list.
data <- resp |> resp_body_json()
print(data$name)
# [1] "pikachu"
print(data$weight)
# [1] 60
There it is. resp_body_json() handles the heavy lifting of converting the JSON string into an R list. It's a clean transition. But wait—what if I want to look up a different Pokémon without hardcoding the URL every single time? That's where we can start getting more programmatic.
Building a flexible request
I could just use paste0() to build the URL, but that's brittle and prone to encoding errors. httr2 has a better way to handle path segments and query parameters. Let's try to build a request for "Ditto" using a slightly more structured approach.
pokemon_name <- "ditto"
req <- request("https://pokeapi.co/api/v2/pokemon/") |>
req_url_path_append(pokemon_name)
resp <- req |> req_perform()
data <- resp |> resp_body_json()
print(data$abilities[[1]]$ability$name)
# [1] "limber"
I like req_url_path_append() because it handles the slashes correctly. If I had needed to add a query parameter (like ?limit=20), I would have used req_url_query(). It keeps the base URL clean and the modifications explicit.
When things go south
Now, let's see what happens when I make a mistake. I'll try to request a Pokémon that definitely doesn't exist.
req <- request("https://pokeapi.co/api/v2/pokemon/not-a-real-pokemon")
resp <- req |> req_perform()
Boom. R throws a loud error: HTTP 404 Not Found. In a real production script, a 404 shouldn't necessarily crash your entire program. You might want to handle that gracefully.
One way to deal with this is using req_retry() for transient errors (like 503s), but for a 404, we usually wrap the call in a tryCatch() or check the status. However, httr2 provides req_error() to customize how it reacts to these codes. If I want the request to just "fail silently" or return the response anyway without throwing a hard error, I can tell it to ignore certain status codes.
req <- request("https://pokeapi.co/api/v2/pokemon/not-a-real-pokemon") |>
req_error(is_error = function(resp) FALSE)
resp <- req |> req_perform()
print(resp$status)
# [1] 404
Now the code keeps running. I can check the status code and decide what to do next—maybe log a warning or skip to the next item in a loop. It's much more controlled than letting R stop the world because of a missing API resource.
📋 Practical Task
Building a Pokémon Stat Extractor
Write a function called get_pokemon_stats that takes a Pokémon's name as a string argument. The function should:
- Construct a request to
https://pokeapi.co/api/v2/pokemon/usingreq_url_path_append(). - Perform the request and parse the JSON body.
- Return a small named list containing only the
name,height, andweightof the Pokémon. - Use
tryCatch()orreq_error()to ensure that if a Pokémon isn't found (404), the function returnsNULLinstead of crashing.
Test your function with "mewtwo" (which should work) and "agumon" (which should return NULL).
There are no comments for now.