rest_api: Get data from a REST API

View source: R/api.R

rest_apiR Documentation

Get data from a REST API

Description

Read data from a REST API and optionally with an authorization token in the request header. The function rest_api_raw() returns the raw text of the response, and rest_api() will parse the response with jsonlite::fromJSON() (assuming that the response is in the JSON format).

Usage

rest_api(...)

rest_api_raw(root, endpoint, token = "", params = list(), headers = NULL)

github_api(
  endpoint,
  token = "",
  params = list(),
  headers = NULL,
  raw = !loadable("jsonlite")
)

Arguments

...

Arguments to be passed to rest_api_raw().

root

The API root URL.

endpoint

The API endpoint.

token

A named character string (e.g., c(token = "xxxx")), which will be used to create an authorization header of the form Authorization: NAME TOKEN for the API call, where NAME is the name of the string and TOKEN is the string. If the string does not have a name, Basic will be used as the default name.

params

A list of query parameters to be sent with the API call.

headers

A named character vector of HTTP headers, e.g., c(Accept = "application/vnd.github.v3+json").

raw

Whether to return the raw response or parse the response with jsonlite.

Details

These functions are simple wrappers based on url() and read_utf8(). Specifically, the headers argument is passed to url(), and read_utf8() will send a GET request to the API server. This means these functions only support the GET method. If you need to use other HTTP methods (such as POST), you have to use other packages such as curl and httr.

github_api() is a wrapper function based on rest_api_raw() to obtain data from the Github API: https://docs.github.com/en/rest. You can provide a personal access token (PAT) via the token argument, or via one of the environment variables GITHUB_PAT, GITHUB_TOKEN, GH_TOKEN. A PAT allows for a much higher rate limit in API calls. Without a token, you can only make 60 calls in an hour.

Value

A character vector (the raw JSON response) or an R object parsed from the JSON text.

Examples

# a normal GET request
xfun::rest_api("https://httpbin.org", "/get")
xfun::rest_api_raw("https://httpbin.org", "/get")

# send the request with an auth header
xfun::rest_api("https://httpbin.org", "/headers", "OPEN SESAME!")

# with query parameters
xfun::rest_api("https://httpbin.org", "/response-headers", params = list(foo = "bar"))

# get the rate limit info from Github
xfun::github_api("/rate_limit")


xfun documentation built on Nov. 17, 2022, 1:06 a.m.