rest_api: Get data from a REST API

View source: R/api.R

rest_apiR Documentation

Get data from a REST API


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).



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

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



Arguments to be passed to rest_api_raw().


The API root URL.


The API endpoint.


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.


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


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


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


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: 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.


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


# a normal GET request
xfun::rest_api("", "/get")
xfun::rest_api_raw("", "/get")

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

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

# get the rate limit info from Github

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