Skip to Content
Course content

227: Consuming REST APIs from R with httr2

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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/ using req_url_path_append().
  • Perform the request and parse the JSON body.
  • Return a small named list containing only the name, height, and weight of the Pokémon.
  • Use tryCatch() or req_error() to ensure that if a Pokémon isn't found (404), the function returns NULL instead of crashing.

Test your function with "mewtwo" (which should work) and "agumon" (which should return NULL).

Rating
0 0

There are no comments for now.

to be the first to leave a comment.