使用R httr2 调用API

Using R httr2 to call API

Tool
R
Author

Tony D

Published

March 15, 2025

A guide to using the httr2 R package for interacting with web APIs, with examples for the US National Weather Service and OpenWeatherMap APIs.

This document provides a practical guide to using the httr2 package in R for interacting with web APIs. It includes two detailed examples: one that demonstrates how to call the US National Weather Service (NWS) API to retrieve hourly weather forecasts, and another that shows how to use the OpenWeatherMap API to get current weather data for a specific city. The guide covers the entire process, from constructing the API request to performing the request and extracting the relevant data from the JSON response.

The httr2 package provides a pipeable API for working with web APIs.

Example 1: call US weather API

Code
pak::pkg_install('httr2')

https://api.weather.gov/points/38.8894,-77.0352

Code
library(httr2)
library(tidyverse)

create response and check connection

Code
NWS_response=NWS_response_link|> req_perform()
NWS_response

get forecast hourly url from response

Code
NWS_response |> 
  resp_body_json() |> 
  glimpse()
Code
forecast_url <- NWS_response |> 
  resp_body_json() |> 
  pluck('properties', 'forecastHourly')

forecast_url

make forecast hourly response

Code
forecast_response <- request(forecast_url) |> 
  req_perform()

forecast_response |> 
  resp_body_json() |> 
  glimpse()

get forecast hourly data

Code
extracted_data <- forecast_response |> 
  resp_body_json() |> 
  pluck('properties', 'periods') |> 
  map_dfr( # iterates over each list and binds rows to a tibble
    \(x) {
      tibble(
        time = x |> pluck('startTime'),
        temp_F = x |> pluck('temperature'),
        rain_prob = x |> pluck('probabilityOfPrecipitation', 'value'),
        forecast = x |> pluck('shortForecast')
      )
    }
  )

extracted_data

Example 2 :openweathermap

https://home.openweathermap.org/

Code
pak::pkg_install('httr2')
Code
library(httr2)

create response

Code
library(keyring)
openweathermap_base_url <- 'https://api.openweathermap.org/data/2.5'

openweathermap_api_key=key_get("openweathermap_api_key")

city='Bangkok'

openweathermap_response_link <- request(openweathermap_base_url) |> 
  req_url_path_append(
    paste0('weather?q=',city,'&appid=',openweathermap_api_key,'&units=metric')
  ) 

openweathermap_response_link
Code
openweathermap_response=openweathermap_response_link|> req_perform()
openweathermap_response

get data from response

Code
openweathermap_response |> 
  resp_body_json() |> 
  glimpse()
Code
openweathermap_response |> 
  resp_body_json() |> 
  pluck('main', 'temp') 

a=openweathermap_response |> 
  resp_body_json() |> 
  pluck('weather') 

(a[[1]])$main

openweathermap_response |> 
  resp_body_json() |> 
  pluck('name') 

openweathermap_response |> 
  resp_body_json() |> 
  pluck('coord', 'lon') 

openweathermap_response |> 
  resp_body_json() |> 
  pluck('coord', 'lat') 

London air_pollution:

http://api.openweathermap.org/data/2.5/air_pollution?lat=51.5085&lon=-0.1257&appid=625ae405e4f11b5b957af484b77fbd62

Reference

https://httr2.r-lib.org/

https://www.youtube.com/watch?v=8tilyqp4bZY

https://www.youtube.com/watch?v=hmtE4QGIOuk

https://openweathermap.org/current