...

Text file src/github.com/google/go-github/v45/README.md

Documentation: github.com/google/go-github/v45

     1# go-github #
     2
     3[![go-github release (latest SemVer)](https://img.shields.io/github/v/release/google/go-github?sort=semver)](https://github.com/google/go-github/releases)
     4[![GoDoc](https://img.shields.io/static/v1?label=godoc&message=reference&color=blue)](https://pkg.go.dev/github.com/google/go-github/v45/github)
     5[![Test Status](https://github.com/google/go-github/workflows/tests/badge.svg)](https://github.com/google/go-github/actions?query=workflow%3Atests)
     6[![Test Coverage](https://codecov.io/gh/google/go-github/branch/master/graph/badge.svg)](https://codecov.io/gh/google/go-github)
     7[![Discuss at go-github@googlegroups.com](https://img.shields.io/badge/discuss-go--github%40googlegroups.com-blue.svg)](https://groups.google.com/group/go-github)
     8[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/796/badge)](https://bestpractices.coreinfrastructure.org/projects/796)
     9
    10go-github is a Go client library for accessing the [GitHub API v3][].
    11
    12Currently, **go-github requires Go version 1.13 or greater**.  go-github tracks
    13[Go's version support policy][support-policy].  We do our best not to break
    14older versions of Go if we don't have to, but due to tooling constraints, we
    15don't always test older versions.
    16
    17[support-policy]: https://golang.org/doc/devel/release.html#policy
    18
    19If you're interested in using the [GraphQL API v4][], the recommended library is
    20[shurcooL/githubv4][].
    21
    22## Installation ##
    23
    24go-github is compatible with modern Go releases in module mode, with Go installed:
    25
    26```bash
    27go get github.com/google/go-github/v45
    28```
    29
    30will resolve and add the package to the current development module, along with its dependencies.
    31
    32Alternatively the same can be achieved if you use import in a package:
    33
    34```go
    35import "github.com/google/go-github/v45/github"
    36```
    37
    38and run `go get` without parameters.
    39
    40Finally, to use the top-of-trunk version of this repo, use the following command:
    41
    42```bash
    43go get github.com/google/go-github/v45@master
    44```
    45
    46## Usage ##
    47
    48```go
    49import "github.com/google/go-github/v45/github"	// with go modules enabled (GO111MODULE=on or outside GOPATH)
    50import "github.com/google/go-github/github" // with go modules disabled
    51```
    52
    53Construct a new GitHub client, then use the various services on the client to
    54access different parts of the GitHub API. For example:
    55
    56```go
    57client := github.NewClient(nil)
    58
    59// list all organizations for user "willnorris"
    60orgs, _, err := client.Organizations.List(context.Background(), "willnorris", nil)
    61```
    62
    63Some API methods have optional parameters that can be passed. For example:
    64
    65```go
    66client := github.NewClient(nil)
    67
    68// list public repositories for org "github"
    69opt := &github.RepositoryListByOrgOptions{Type: "public"}
    70repos, _, err := client.Repositories.ListByOrg(context.Background(), "github", opt)
    71```
    72
    73The services of a client divide the API into logical chunks and correspond to
    74the structure of the GitHub API documentation at
    75https://docs.github.com/en/rest .
    76
    77NOTE: Using the [context](https://godoc.org/context) package, one can easily
    78pass cancelation signals and deadlines to various services of the client for
    79handling a request. In case there is no context available, then `context.Background()`
    80can be used as a starting point.
    81
    82For more sample code snippets, head over to the
    83[example](https://github.com/google/go-github/tree/master/example) directory.
    84
    85### Authentication ###
    86
    87The go-github library does not directly handle authentication. Instead, when
    88creating a new client, pass an `http.Client` that can handle authentication for
    89you. The easiest and recommended way to do this is using the [oauth2][]
    90library, but you can always use any other library that provides an
    91`http.Client`. If you have an OAuth2 access token (for example, a [personal
    92API token][]), you can use it with the oauth2 library using:
    93
    94```go
    95import "golang.org/x/oauth2"
    96
    97func main() {
    98	ctx := context.Background()
    99	ts := oauth2.StaticTokenSource(
   100		&oauth2.Token{AccessToken: "... your access token ..."},
   101	)
   102	tc := oauth2.NewClient(ctx, ts)
   103
   104	client := github.NewClient(tc)
   105
   106	// list all repositories for the authenticated user
   107	repos, _, err := client.Repositories.List(ctx, "", nil)
   108}
   109```
   110
   111Note that when using an authenticated Client, all calls made by the client will
   112include the specified OAuth token. Therefore, authenticated clients should
   113almost never be shared between different users.
   114
   115See the [oauth2 docs][] for complete instructions on using that library.
   116
   117For API methods that require HTTP Basic Authentication, use the
   118[`BasicAuthTransport`](https://godoc.org/github.com/google/go-github/github#BasicAuthTransport).
   119
   120GitHub Apps authentication can be provided by the [ghinstallation](https://github.com/bradleyfalzon/ghinstallation)
   121package.
   122
   123```go
   124import (
   125	"github.com/bradleyfalzon/ghinstallation/v2"
   126	"github.com/google/go-github/v45/github"
   127)
   128
   129func main() {
   130	// Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99.
   131	itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem")
   132	if err != nil {
   133		// Handle error.
   134	}
   135
   136	// Use installation transport with client.
   137	client := github.NewClient(&http.Client{Transport: itr})
   138
   139	// Use client...
   140}
   141```
   142
   143*Note*: In order to interact with certain APIs, for example writing a file to a repo, one must generate an installation token
   144using the installation ID of the GitHub app and authenticate with the OAuth method mentioned above. See the examples.
   145
   146### Rate Limiting ###
   147
   148GitHub imposes a rate limit on all API clients. Unauthenticated clients are
   149limited to 60 requests per hour, while authenticated clients can make up to
   1505,000 requests per hour. The Search API has a custom rate limit. Unauthenticated
   151clients are limited to 10 requests per minute, while authenticated clients
   152can make up to 30 requests per minute. To receive the higher rate limit when
   153making calls that are not issued on behalf of a user,
   154use `UnauthenticatedRateLimitedTransport`.
   155
   156The returned `Response.Rate` value contains the rate limit information
   157from the most recent API call. If a recent enough response isn't
   158available, you can use `RateLimits` to fetch the most up-to-date rate
   159limit data for the client.
   160
   161To detect an API rate limit error, you can check if its type is `*github.RateLimitError`:
   162
   163```go
   164repos, _, err := client.Repositories.List(ctx, "", nil)
   165if _, ok := err.(*github.RateLimitError); ok {
   166	log.Println("hit rate limit")
   167}
   168```
   169
   170Learn more about GitHub rate limiting at
   171https://docs.github.com/en/rest/rate-limit .
   172
   173### Accepted Status ###
   174
   175Some endpoints may return a 202 Accepted status code, meaning that the
   176information required is not yet ready and was scheduled to be gathered on
   177the GitHub side. Methods known to behave like this are documented specifying
   178this behavior.
   179
   180To detect this condition of error, you can check if its type is
   181`*github.AcceptedError`:
   182
   183```go
   184stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo)
   185if _, ok := err.(*github.AcceptedError); ok {
   186	log.Println("scheduled on GitHub side")
   187}
   188```
   189
   190### Conditional Requests ###
   191
   192The GitHub API has good support for conditional requests which will help
   193prevent you from burning through your rate limit, as well as help speed up your
   194application. `go-github` does not handle conditional requests directly, but is
   195instead designed to work with a caching `http.Transport`. We recommend using
   196https://github.com/gregjones/httpcache for that.
   197
   198Learn more about GitHub conditional requests at
   199https://docs.github.com/en/rest/overview/resources-in-the-rest-api#conditional-requests.
   200
   201### Creating and Updating Resources ###
   202
   203All structs for GitHub resources use pointer values for all non-repeated fields.
   204This allows distinguishing between unset fields and those set to a zero-value.
   205Helper functions have been provided to easily create these pointers for string,
   206bool, and int values. For example:
   207
   208```go
   209// create a new private repository named "foo"
   210repo := &github.Repository{
   211	Name:    github.String("foo"),
   212	Private: github.Bool(true),
   213}
   214client.Repositories.Create(ctx, "", repo)
   215```
   216
   217Users who have worked with protocol buffers should find this pattern familiar.
   218
   219### Pagination ###
   220
   221All requests for resource collections (repos, pull requests, issues, etc.)
   222support pagination. Pagination options are described in the
   223`github.ListOptions` struct and passed to the list methods directly or as an
   224embedded type of a more specific list options struct (for example
   225`github.PullRequestListOptions`). Pages information is available via the
   226`github.Response` struct.
   227
   228```go
   229client := github.NewClient(nil)
   230
   231opt := &github.RepositoryListByOrgOptions{
   232	ListOptions: github.ListOptions{PerPage: 10},
   233}
   234// get all pages of results
   235var allRepos []*github.Repository
   236for {
   237	repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt)
   238	if err != nil {
   239		return err
   240	}
   241	allRepos = append(allRepos, repos...)
   242	if resp.NextPage == 0 {
   243		break
   244	}
   245	opt.Page = resp.NextPage
   246}
   247```
   248
   249### Webhooks ###
   250
   251`go-github` provides structs for almost all [GitHub webhook events][] as well as functions to validate them and unmarshal JSON payloads from `http.Request` structs.
   252
   253```go
   254func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   255	payload, err := github.ValidatePayload(r, s.webhookSecretKey)
   256	if err != nil { ... }
   257	event, err := github.ParseWebHook(github.WebHookType(r), payload)
   258	if err != nil { ... }
   259	switch event := event.(type) {
   260	case *github.CommitCommentEvent:
   261		processCommitCommentEvent(event)
   262	case *github.CreateEvent:
   263		processCreateEvent(event)
   264	...
   265	}
   266}
   267```
   268
   269Furthermore, there are libraries like [cbrgm/githubevents][] that build upon the example above and provide functions to subscribe callbacks to specific events.
   270
   271For complete usage of go-github, see the full [package docs][].
   272
   273[GitHub API v3]: https://docs.github.com/en/rest
   274[oauth2]: https://github.com/golang/oauth2
   275[oauth2 docs]: https://godoc.org/golang.org/x/oauth2
   276[personal API token]: https://github.com/blog/1509-personal-api-tokens
   277[package docs]: https://pkg.go.dev/github.com/google/go-github/v45/github
   278[GraphQL API v4]: https://developer.github.com/v4/
   279[shurcooL/githubv4]: https://github.com/shurcooL/githubv4
   280[GitHub webhook events]: https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads
   281[cbrgm/githubevents]: https://github.com/cbrgm/githubevents
   282
   283### Testing code that uses `go-github`
   284
   285The repo [migueleliasweb/go-github-mock](https://github.com/migueleliasweb/go-github-mock) provides a way to mock responses. Check the repo for more details.
   286
   287### Integration Tests ###
   288
   289You can run integration tests from the `test` directory. See the integration tests [README](test/README.md).
   290
   291## Contributing ##
   292I would like to cover the entire GitHub API and contributions are of course always welcome. The
   293calling pattern is pretty well established, so adding new methods is relatively
   294straightforward. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for details.
   295
   296## Versioning ##
   297
   298In general, go-github follows [semver](https://semver.org/) as closely as we
   299can for tagging releases of the package. For self-contained libraries, the
   300application of semantic versioning is relatively straightforward and generally
   301understood. But because go-github is a client library for the GitHub API, which
   302itself changes behavior, and because we are typically pretty aggressive about
   303implementing preview features of the GitHub API, we've adopted the following
   304versioning policy:
   305
   306* We increment the **major version** with any incompatible change to
   307	non-preview functionality, including changes to the exported Go API surface
   308	or behavior of the API.
   309* We increment the **minor version** with any backwards-compatible changes to
   310	functionality, as well as any changes to preview functionality in the GitHub
   311	API. GitHub makes no guarantee about the stability of preview functionality,
   312	so neither do we consider it a stable part of the go-github API.
   313* We increment the **patch version** with any backwards-compatible bug fixes.
   314
   315Preview functionality may take the form of entire methods or simply additional
   316data returned from an otherwise non-preview method. Refer to the GitHub API
   317documentation for details on preview functionality.
   318
   319## License ##
   320
   321This library is distributed under the BSD-style license found in the [LICENSE](./LICENSE)
   322file.

View as plain text