rest_api | R Documentation |
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")
)
... |
Arguments to be passed to |
root |
The API root URL. |
endpoint |
The API endpoint. |
token |
A named character string (e.g., |
params |
A list of query parameters to be sent with the API call. |
headers |
A named character vector of HTTP headers, e.g., |
raw |
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.
A character vector (the raw JSON response) or an R object parsed from the JSON text.
# 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")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.