Making HTTP Requests with httr2
Send GET and POST requests, handle headers, and process responses.
Introduction to httr2
httr2 is the modern R package for HTTP requests, succeeding httr. It uses a pipe-based builder pattern: start with request(url), add modifiers, then execute with req_perform().
library(httr2)
# Basic GET request pattern:
# request(url) -> create request object
# |> req_*() -> modify request
# |> req_perform() -> send request
# |> resp_*() -> extract from response
# Minimal example (requires internet):
# resp <- request('https://httpbin.org/get') |>
# req_perform()
# resp_status(resp) # 200
# resp_body_json(resp) # parsed JSON body
cat('httr2 follows: build -> perform -> extract')request() and req_perform()
request(url) creates a request object. req_perform() executes it and returns a response object. The response can then be inspected with resp_* functions.
library(httr2)
# Build and send a GET request
# resp <- request('https://httpbin.org/get') |>
# req_perform()
# Inspect response
# resp_status(resp) # 200
# resp_status_desc(resp) # 'OK'
# resp_headers(resp) # list of headers
# resp_header(resp, 'content-type') # single header
# resp_body_string(resp) # raw body as string
# resp_body_json(resp) # parsed JSON
# resp_body_raw(resp) # raw bytes
cat('Response hierarchy:')
cat('status -> headers -> body')All lessons in this course
- Parsing JSON with jsonlite
- Making HTTP Requests with httr2
- Consuming REST APIs in R
- Handling Nested JSON Structures