Title: | 'GitHub' 'API' |
---|---|
Description: | Minimal client to access the 'GitHub' 'API'. |
Authors: | Gábor Csárdi [cre, ctb], Jennifer Bryan [aut], Hadley Wickham [aut], Posit Software, PBC [cph, fnd] |
Maintainer: | Gábor Csárdi <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.4.1.9000 |
Built: | 2024-10-25 14:14:59 UTC |
Source: | https://github.com/r-lib/gh |
This is an extremely minimal client. You need to know the API to be able to use this client. All this function does is:
Try to substitute each listed parameter into endpoint
, using the
{parameter}
notation.
If a GET request (the default), then add all other listed parameters as query parameters.
If not a GET request, then send the other parameters in the request body, as JSON.
Convert the response to an R list using jsonlite::fromJSON()
.
gh( endpoint, ..., per_page = NULL, .per_page = NULL, .token = NULL, .destfile = NULL, .overwrite = FALSE, .api_url = NULL, .method = "GET", .limit = NULL, .accept = "application/vnd.github.v3+json", .send_headers = NULL, .progress = TRUE, .params = list(), .max_wait = 600, .max_rate = NULL )
gh( endpoint, ..., per_page = NULL, .per_page = NULL, .token = NULL, .destfile = NULL, .overwrite = FALSE, .api_url = NULL, .method = "GET", .limit = NULL, .accept = "application/vnd.github.v3+json", .send_headers = NULL, .progress = TRUE, .params = list(), .max_wait = 600, .max_rate = NULL )
endpoint |
GitHub API endpoint. Must be one of the following forms:
If the method is not supplied, will use |
... |
Name-value pairs giving API parameters. Will be matched into
|
per_page , .per_page
|
Number of items to return per page. If omitted,
will be substituted by |
.token |
Authentication token. Defaults to |
.destfile |
Path to write response to disk. If |
.overwrite |
If |
.api_url |
Github API url (default: https://api.github.com). Used
if |
.method |
HTTP method to use if not explicitly supplied in the
|
.limit |
Number of records to return. This can be used
instead of manual pagination. By default it is |
.accept |
The value of the |
.send_headers |
Named character vector of header field values
(except |
.progress |
Whether to show a progress indicator for calls that need more than one HTTP request. |
.params |
Additional list of parameters to append to |
.max_wait |
Maximum number of seconds to wait if rate limited. Defaults to 10 minutes. |
.max_rate |
Maximum request rate in requests per second. Set this to automatically throttle requests. |
Answer from the API as a gh_response
object, which is also a
list
. Failed requests will generate an R error. Requests that
generate a raw response will return a raw vector.
gh_gql()
if you want to use the GitHub GraphQL API,
gh_whoami()
for details on GitHub API token management.
## Repositories of a user, these are equivalent gh("/users/hadley/repos", .limit = 2) gh("/users/{username}/repos", username = "hadley", .limit = 2) ## Starred repositories of a user gh("/users/hadley/starred", .limit = 2) gh("/users/{username}/starred", username = "hadley", .limit = 2) ## Create a repository, needs a token (see gh_token()) gh("POST /user/repos", name = "foobar") ## Issues of a repository gh("/repos/hadley/dplyr/issues") gh("/repos/{owner}/{repo}/issues", owner = "hadley", repo = "dplyr") ## Automatic pagination users <- gh("/users", .limit = 50) length(users) ## Access developer preview of Licenses API (in preview as of 2015-09-24) gh("/licenses") # used to error code 415 gh("/licenses", .accept = "application/vnd.github.drax-preview+json") ## Access Github Enterprise API ## Use GITHUB_API_URL environment variable to change the default. gh("/user/repos", type = "public", .api_url = "https://github.foobar.edu/api/v3") ## Use I() to force body part to be sent as an array, even if length 1 ## This works whether assignees has length 1 or > 1 assignees <- "gh_user" assignees <- c("gh_user1", "gh_user2") gh("PATCH /repos/OWNER/REPO/issues/1", assignees = I(assignees)) ## There are two ways to send JSON data. One is that you supply one or ## more objects that will be converted to JSON automatically via ## jsonlite::toJSON(). In this case sometimes you need to use ## jsonlite::unbox() because fromJSON() creates lists from scalar vectors ## by default. The Content-Type header is automatically added in this ## case. For example this request turns on GitHub Pages, using this ## API: https://docs.github.com/v3/repos/pages/#enable-a-pages-site gh::gh( "POST /repos/{owner}/{repo}/pages", owner = "r-lib", repo = "gh", source = list( branch = jsonlite::unbox("gh-pages"), path = jsonlite::unbox("/") ), .send_headers = c(Accept = "application/vnd.github.switcheroo-preview+json") ) ## The second way is to handle the JSON encoding manually, and supply it ## as a raw vector in an unnamed argument, and also a Content-Type header: body <- '{ "source": { "branch": "gh-pages", "path": "/" } }' gh::gh( "POST /repos/{owner}/{repo}/pages", owner = "r-lib", repo = "gh", charToRaw(body), .send_headers = c( Accept = "application/vnd.github.switcheroo-preview+json", "Content-Type" = "application/json" ) ) ## Pass along a query to the search/code endpoint via the ... argument x <- gh::gh( "/search/code", q = "installation repo:r-lib/gh", .send_headers = c("X-GitHub-Api-Version" = "2022-11-28") ) str(x, list.len = 3, give.attr = FALSE)
## Repositories of a user, these are equivalent gh("/users/hadley/repos", .limit = 2) gh("/users/{username}/repos", username = "hadley", .limit = 2) ## Starred repositories of a user gh("/users/hadley/starred", .limit = 2) gh("/users/{username}/starred", username = "hadley", .limit = 2) ## Create a repository, needs a token (see gh_token()) gh("POST /user/repos", name = "foobar") ## Issues of a repository gh("/repos/hadley/dplyr/issues") gh("/repos/{owner}/{repo}/issues", owner = "hadley", repo = "dplyr") ## Automatic pagination users <- gh("/users", .limit = 50) length(users) ## Access developer preview of Licenses API (in preview as of 2015-09-24) gh("/licenses") # used to error code 415 gh("/licenses", .accept = "application/vnd.github.drax-preview+json") ## Access Github Enterprise API ## Use GITHUB_API_URL environment variable to change the default. gh("/user/repos", type = "public", .api_url = "https://github.foobar.edu/api/v3") ## Use I() to force body part to be sent as an array, even if length 1 ## This works whether assignees has length 1 or > 1 assignees <- "gh_user" assignees <- c("gh_user1", "gh_user2") gh("PATCH /repos/OWNER/REPO/issues/1", assignees = I(assignees)) ## There are two ways to send JSON data. One is that you supply one or ## more objects that will be converted to JSON automatically via ## jsonlite::toJSON(). In this case sometimes you need to use ## jsonlite::unbox() because fromJSON() creates lists from scalar vectors ## by default. The Content-Type header is automatically added in this ## case. For example this request turns on GitHub Pages, using this ## API: https://docs.github.com/v3/repos/pages/#enable-a-pages-site gh::gh( "POST /repos/{owner}/{repo}/pages", owner = "r-lib", repo = "gh", source = list( branch = jsonlite::unbox("gh-pages"), path = jsonlite::unbox("/") ), .send_headers = c(Accept = "application/vnd.github.switcheroo-preview+json") ) ## The second way is to handle the JSON encoding manually, and supply it ## as a raw vector in an unnamed argument, and also a Content-Type header: body <- '{ "source": { "branch": "gh-pages", "path": "/" } }' gh::gh( "POST /repos/{owner}/{repo}/pages", owner = "r-lib", repo = "gh", charToRaw(body), .send_headers = c( Accept = "application/vnd.github.switcheroo-preview+json", "Content-Type" = "application/json" ) ) ## Pass along a query to the search/code endpoint via the ... argument x <- gh::gh( "/search/code", q = "installation repo:r-lib/gh", .send_headers = c("X-GitHub-Api-Version" = "2022-11-28") ) str(x, list.len = 3, give.attr = FALSE)
See more about the GraphQL API here: https://docs.github.com/graphql
gh_gql(query, ...)
gh_gql(query, ...)
query |
The GraphQL query, as a string. |
... |
Name-value pairs giving API parameters. Will be matched into
|
Note: pagination and the .limit
argument does not work currently,
as pagination in the GraphQL API is different from the v3 API.
If you need pagination with GraphQL, you'll need to do that manually.
gh()
for the GitHub v3 API.
gh_gql("query { viewer { login }}") # Get rate limit ratelimit_query <- "query { viewer { login } rateLimit { limit cost remaining resetAt } }" gh_gql(ratelimit_query)
gh_gql("query { viewer { login }}") # Get rate limit ratelimit_query <- "query { viewer { login } rateLimit { limit cost remaining resetAt } }" gh_gql(ratelimit_query)
Get the next, previous, first or last page of results
gh_next(gh_response) gh_prev(gh_response) gh_first(gh_response) gh_last(gh_response)
gh_next(gh_response) gh_prev(gh_response) gh_first(gh_response) gh_last(gh_response)
gh_response |
An object returned by a |
Note that these are not always defined. E.g. if the first page was queried (the default), then there are no first and previous pages defined. If there is no next page, then there is no next page defined, etc.
If the requested page does not exist, an error is thrown.
Answer from the API.
The .limit
argument to gh()
supports fetching more than
one page.
x <- gh("/users") vapply(x, "[[", character(1), "login") x2 <- gh_next(x) vapply(x2, "[[", character(1), "login")
x <- gh("/users") vapply(x, "[[", character(1), "login") x2 <- gh_next(x) vapply(x2, "[[", character(1), "login")
gh_rate_limits()
reports on all rate limits for the authenticated user.
gh_rate_limit()
reports on rate limits for previous successful request.
Further details on GitHub's API rate limit policies are available at https://docs.github.com/v3/#rate-limiting.
gh_rate_limit( response = NULL, .token = NULL, .api_url = NULL, .send_headers = NULL ) gh_rate_limits(.token = NULL, .api_url = NULL, .send_headers = NULL)
gh_rate_limit( response = NULL, .token = NULL, .api_url = NULL, .send_headers = NULL ) gh_rate_limits(.token = NULL, .api_url = NULL, .send_headers = NULL)
response |
|
.token |
Authentication token. Defaults to |
.api_url |
Github API url (default: https://api.github.com). Used
if |
.send_headers |
Named character vector of header field values
(except |
A list
object containing the overall limit
, remaining
limit, and the
limit reset
time.
If gh can find a personal access token (PAT) via gh_token()
, it includes
the PAT in its requests. Some requests succeed without a PAT, but many
require a PAT to prove the request is authorized by a specific GitHub user. A
PAT also helps with rate limiting. If your gh use is more than casual, you
want a PAT.
gh calls gitcreds::gitcreds_get()
with the api_url
, which checks session
environment variables (GITHUB_PAT
, GITHUB_TOKEN
)
and then the local Git credential store for a PAT
appropriate to the api_url
. Therefore, if you have previously used a PAT
with, e.g., command line Git, gh may retrieve and re-use it. You can call
gitcreds::gitcreds_get()
directly, yourself, if you want to see what is
found for a specific URL. If no matching PAT is found,
gitcreds::gitcreds_get()
errors, whereas gh_token()
does not and,
instead, returns ""
.
See GitHub's documentation on Creating a personal access token,
or use usethis::create_github_token()
for a guided experience, including
pre-selection of recommended scopes. Once you have a PAT, you can use
gitcreds::gitcreds_set()
to add it to the Git credential store. From that
point on, gh (via gitcreds::gitcreds_get()
) should be able to find it
without further effort on your part.
gh_token(api_url = NULL) gh_token_exists(api_url = NULL)
gh_token(api_url = NULL) gh_token_exists(api_url = NULL)
api_url |
GitHub API URL. Defaults to the |
A string of characters, if a PAT is found, or the empty string, otherwise. For convenience, the return value has an S3 class in order to ensure that simple printing strategies don't reveal the entire PAT.
## Not run: gh_token() format(gh_token()) str(gh_token()) ## End(Not run)
## Not run: gh_token() format(gh_token()) str(gh_token()) ## End(Not run)
This is handy helper if you want to make gh requests related to the current project.
gh_tree_remote(path = ".")
gh_tree_remote(path = ".")
path |
Path that is contained within a git repo. |
If the repo has a github remote, a list containing username
and repo
. Otherwise, an error.
gh_tree_remote()
gh_tree_remote()
Reports wallet name, GitHub login, and GitHub URL for the current authenticated user, the first bit of the token, and the associated scopes.
gh_whoami(.token = NULL, .api_url = NULL, .send_headers = NULL)
gh_whoami(.token = NULL, .api_url = NULL, .send_headers = NULL)
.token |
Authentication token. Defaults to |
.api_url |
Github API url (default: https://api.github.com). Used
if |
.send_headers |
Named character vector of header field values
(except |
Get a personal access token for the GitHub API from
https://github.com/settings/tokens and select the scopes necessary for your
planned tasks. The repo
scope, for example, is one many are likely to need.
On macOS and Windows it is best to store the token in the git credential store, where most GitHub clients, including gh, can access it. You can use the gitcreds package to add your token to the credential store:
gitcreds::gitcreds_set()
See https://gh.r-lib.org/articles/managing-personal-access-tokens.html and https://usethis.r-lib.org/articles/articles/git-credentials.html for more about managing GitHub (and generic git) credentials.
On other systems, including Linux, the git credential store is
typically not as convenient, and you might want to store your token in
the GITHUB_PAT
environment variable, which you can set in your
.Renviron
file.
A gh_response
object, which is also a list
.
gh_whoami() ## explicit token + use with GitHub Enterprise gh_whoami( .token = "8c70fd8419398999c9ac5bacf3192882193cadf2", .api_url = "https://github.foobar.edu/api/v3" )
gh_whoami() ## explicit token + use with GitHub Enterprise gh_whoami( .token = "8c70fd8419398999c9ac5bacf3192882193cadf2", .api_url = "https://github.foobar.edu/api/v3" )
Print the result of a GitHub API call
## S3 method for class 'gh_response' print(x, ...)
## S3 method for class 'gh_response' print(x, ...)
x |
The result object. |
... |
Ignored. |
The JSON result.