Invio di richieste HTTP con httr2
Invii richieste GET e POST, gestisca le intestazioni ed elabori le risposte
Invio di richieste HTTP con httr2 è una lezione R Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento R Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso R Academy include 4 lezioni in totale.
Introduzione a httr2
httr2 è il moderno pacchetto R per le richieste HTTP e il successore di httr. Utilizza un pattern builder basato sulle pipe: si inizia con request(url), si aggiungono modificatori e infine si esegue la richiesta con 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() e req_perform()
request(url) crea un oggetto richiesta. req_perform() lo esegue e restituisce un oggetto risposta. È quindi possibile esaminare la risposta con le funzioni resp_*.
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')req_headers(): intestazioni personalizzate
req_headers() aggiunge o sostituisce le intestazioni HTTP. Viene utilizzata per i token di autenticazione, la specifica del tipo di contenuto, le intestazioni della versione dell'API e i metadati personalizzati della richiesta.
library(httr2)
# Add custom headers
# resp <- request('https://api.example.com/data') |>
# req_headers(
# 'Authorization' = 'Bearer my_token',
# 'X-API-Version' = '2',
# 'Accept' = 'application/json'
# ) |>
# req_perform()
# Common headers:
# 'Content-Type' = 'application/json' for POST with JSON body
# 'Accept' = 'application/json' to request JSON response
# 'User-Agent' = 'MyApp/1.0' for polite identification
# 'X-API-Key' = key for key-based auth
cat('req_headers() sets HTTP request headers')req_url_query(): parametri di query
req_url_query() aggiunge in modo sicuro i parametri di query all'URL, codificando i caratteri speciali. È più pulito che concatenare manualmente le stringhe con paste0().
library(httr2)
# Add query parameters
# resp <- request('https://api.example.com/search') |>
# req_url_query(
# q = 'R programming',
# page = 1,
# size = 20,
# sort = 'relevance'
# ) |>
# req_perform()
# Resulting URL:
# https://api.example.com/search?q=R+programming&page=1&size=20&sort=relevance
# Inspect the URL without performing:
req <- request('https://api.example.com/search') |>
req_url_query(q = 'hello world', page = 2)
req$url
# 'https://api.example.com/search?q=hello+world&page=2'Richieste POST con req_body_json()
Invii dati JSON in una richiesta POST con req_body_json(). La funzione imposta automaticamente l'intestazione Content-Type: application/json e serializza la lista R in JSON.
library(httr2)
# POST request with JSON body
# resp <- request('https://api.example.com/users') |>
# req_method('POST') |>
# req_body_json(list(
# name = 'Alice',
# email = 'alice@example.com',
# role = 'admin'
# )) |>
# req_perform()
# resp_status(resp) # 201 Created (if success)
# resp_body_json(resp) # returned user object
# Other body methods:
# req_body_form(...) -> application/x-www-form-urlencoded
# req_body_raw(bytes) -> raw bytes
# req_body_file(path) -> file upload
cat('req_body_json() handles Content-Type automatically')resp_body_json(): analizzare la risposta
resp_body_json() analizza il corpo della risposta come JSON e lo converte in una lista R. Utilizzi simplifyVector=TRUE (impostazione predefinita) per convertire automaticamente gli array JSON in vettori R e gli oggetti in liste con nome.
library(httr2)
library(jsonlite)
# Simulated API response handling
# resp <- request('https://api.github.com/users/hadley') |>
# req_perform()
# user <- resp_body_json(resp)
# user$name # 'Hadley Wickham'
# user$public_repos # number of repos
# user$followers # follower count
# For arrays (simplifyVector=TRUE converts to data frame):
# resp <- request('https://api.github.com/users/hadley/repos') |>
# req_perform()
# repos <- resp_body_json(resp, simplifyVector = TRUE)
# repos$name # vector of repo names
cat('resp_body_json() with simplifyVector=TRUE -> data frame')resp_status() e gestione degli errori
resp_check_status() genera automaticamente un errore per le risposte 4xx/5xx. Senza questa funzione, httr2 non genera errori per i codici di stato non validi: deve verificare esplicitamente il codice oppure chiamare resp_check_status().
library(httr2)
# Pattern: check status after perform
# resp <- request('https://api.example.com/data') |>
# req_perform() |>
# resp_check_status() # errors on 4xx/5xx
# Manual status checks:
# status <- resp_status(resp)
# if (status == 200) { ... }
# if (status == 404) { stop('Not found') }
# if (status == 401) { stop('Unauthorized') }
# if (status == 429) { Sys.sleep(60); retry() }
# HTTP status codes:
# 200 OK, 201 Created, 204 No Content
# 400 Bad Request, 401 Unauthorized, 403 Forbidden
# 404 Not Found, 429 Rate Limited
# 500 Server Error, 503 Service Unavailable
cat('Always check response status codes')req_retry(): nuovi tentativi automatici
req_retry() ripete automaticamente le richieste non riuscite. Specifichi max_tries e, facoltativamente, is_transient, una funzione che identifica gli errori per i quali è possibile riprovare, come 429 o 503. È essenziale per client API affidabili.
library(httr2)
# Automatic retry with exponential backoff
# resp <- request('https://api.example.com/data') |>
# req_retry(
# max_tries = 3,
# is_transient = function(resp) {
# resp_status(resp) %in% c(429, 500, 503)
# },
# backoff = ~ 2^.x # exponential: 2, 4, 8 seconds
# ) |>
# req_perform()
# Default retry behavior:
# - Retries on 429 Too Many Requests automatically
# - Uses Retry-After header if present
# - max_tries = 1 by default (no retry)
# Simple retry:
# req_retry(max_tries = 3) # retry up to 3 times total
cat('req_retry() adds resilience to API calls')req_throttle(): limitazione della frequenza
req_throttle(rate) garantisce che non venga superata una frequenza massima di richieste. Passi rate = n/period, ad esempio 10 richieste al minuto. httr2 inserisce automaticamente delle pause tra le richieste quando necessario.
library(httr2)
# Throttle to at most 10 requests per minute
# urls <- paste0('https://api.example.com/items/', 1:50)
# resps <- lapply(urls, function(url) {
# request(url) |>
# req_throttle(rate = 10 / 60) |> # 10/min
# req_perform()
# })
# Alternative: use req_perform_parallel() for parallel
# with throttle built in:
# reqs <- lapply(urls, \(u) request(u))
# resps <- req_perform_parallel(
# reqs,
# on_error = 'continue', # skip failures
# progress = TRUE
# )
cat('req_throttle(rate = 10/60) = 10 req/min')Helper per l'autenticazione
httr2 fornisce helper integrati per l'autenticazione: req_auth_basic(user, pass) per l'autenticazione Basic, req_auth_bearer_token(token) per i token Bearer e req_oauth_*() per i flussi OAuth.
library(httr2)
# Bearer token (most common for modern APIs)
# resp <- request('https://api.example.com/data') |>
# req_auth_bearer_token('my_api_token_here') |>
# req_perform()
# Basic authentication
# resp <- request('https://api.example.com/data') |>
# req_auth_basic('username', 'password') |>
# req_perform()
# Store tokens securely in environment variables
# token <- Sys.getenv('MY_API_TOKEN')
# resp <- request('https://api.example.com') |>
# req_auth_bearer_token(token) |>
# req_perform()
cat('Never hardcode tokens in scripts!')
cat('Use Sys.getenv() or the keyring package')Esecuzione a secco con req_dry_run()
req_dry_run() mostra esattamente quale richiesta verrebbe inviata (metodo, URL, intestazioni e corpo) senza inviarla realmente. È essenziale per eseguire il debug di richieste complesse prima di chiamare un'API reale.
library(httr2)
# Inspect the request without sending it
req <- request('https://api.example.com/users') |>
req_method('POST') |>
req_headers(
'X-API-Version' = '2',
'Accept' = 'application/json'
) |>
req_auth_bearer_token('my_token') |>
req_body_json(list(name = 'Alice', role = 'admin')) |>
req_url_query(notify = 'true')
# Show request details without sending
req_dry_run(req)
# POST /users?notify=true HTTP/1.1
# Host: api.example.com
# Authorization: Bearer my_token
# Content-Type: application/json
# ...Verifica rapida
Verifichi la Sua comprensione del pattern di creazione delle richieste di httr2.
Riepilogo: richieste HTTP con httr2
Punti chiave: httr2 utilizza un builder basato sulle pipe: request(url) |> req_*() |> req_perform(). Aggiunga le intestazioni con req_headers(), i parametri di query con req_url_query() e il corpo JSON con req_body_json(). Esegua l'autenticazione con req_auth_bearer_token(). Verifichi sempre lo stato con resp_check_status(). Aggiunga resilienza con req_retry() e limiti la frequenza con req_throttle(). Esegua il debug con req_dry_run().
library(httr2)
# Complete httr2 request pattern:
# resp <- request('https://api.example.com/endpoint') |>
# req_headers('Accept' = 'application/json') |>
# req_url_query(param1 = 'value', page = 1) |>
# req_auth_bearer_token(Sys.getenv('API_TOKEN')) |>
# req_retry(max_tries = 3) |>
# req_throttle(rate = 10/60) |>
# req_perform() |>
# resp_check_status()
# Extract data:
# data <- resp_body_json(resp, simplifyVector = TRUE)
cat('build -> authenticate -> perform -> check -> extract')Domande Frequenti
La lezione «Invio di richieste HTTP con httr2» è gratuita?
Sì — il testo completo di «Invio di richieste HTTP con httr2» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso R Academy, passa a CoddyKit PRO. Il corso R Academy include 4 lezioni in totale.
Cosa imparerò in «Invio di richieste HTTP con httr2»?
Invii richieste GET e POST, gestisca le intestazioni ed elabori le risposte Eserciti R Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare R Academy?
Non è richiesta alcuna esperienza precedente. R Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.
Quanto tempo richiede la lezione «Invio di richieste HTTP con httr2»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione R Academy?
Sì. Ogni lezione R Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Analisi di JSON con jsonlite
- Invio di richieste HTTP con httr2
- Utilizzo di API REST in R
- Gestione di strutture JSON annidate