
Last chance! 50% off unlimited learning
Sale ends in
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(...)rest_api_raw(root, endpoint, token = "", params = list(), headers = NULL)
github_api(
endpoint,
token = "",
params = list(),
headers = NULL,
raw = !loadable("jsonlite")
)
A character vector (the raw JSON response) or an R object parsed from the JSON text.
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:
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.
if (FALSE) { # interactive()
# 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")
}
Run the code above in your browser using DataLab