github.com/google/go-github/v33@v33.0.0/README.md (about)

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