• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/workflows/H02-Dec-2020-

example/H02-Dec-2020-

github/H02-Dec-2020-

scrape/H02-Dec-2020-

test/H02-Dec-2020-

update-urls/H02-Dec-2020-

.codecov.ymlH A D02-Dec-2020124

.gitignoreH A D02-Dec-202066

AUTHORSH A D02-Dec-202010.9 KiB

CONTRIBUTING.mdH A D02-Dec-20206.4 KiB

LICENSEH A D02-Dec-20201.5 KiB

README.mdH A D02-Dec-202010.5 KiB

go.modH A D02-Dec-2020362

go.sumH A D02-Dec-20201.4 KiB

README.md

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
9go-github is a Go client library for accessing the [GitHub API v3][].
10
11Currently, **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
13older versions of Go if we don't have to, but due to tooling constraints, we
14don't always test older versions.
15
16[support-policy]: https://golang.org/doc/devel/release.html#policy
17
18If you're interested in using the [GraphQL API v4][], the recommended library is
19[shurcooL/githubv4][].
20
21## Usage ##
22
23```go
24import "github.com/google/go-github/v33/github"	// with go modules enabled (GO111MODULE=on or outside GOPATH)
25import "github.com/google/go-github/github" // with go modules disabled
26```
27
28Construct a new GitHub client, then use the various services on the client to
29access different parts of the GitHub API. For example:
30
31```go
32client := github.NewClient(nil)
33
34// list all organizations for user "willnorris"
35orgs, _, err := client.Organizations.List(context.Background(), "willnorris", nil)
36```
37
38Some API methods have optional parameters that can be passed. For example:
39
40```go
41client := github.NewClient(nil)
42
43// list public repositories for org "github"
44opt := &github.RepositoryListByOrgOptions{Type: "public"}
45repos, _, err := client.Repositories.ListByOrg(context.Background(), "github", opt)
46```
47
48The services of a client divide the API into logical chunks and correspond to
49the structure of the GitHub API documentation at
50https://docs.github.com/en/free-pro-team@latest/rest/reference/.
51
52NOTE: Using the [context](https://godoc.org/context) package, one can easily
53pass cancelation signals and deadlines to various services of the client for
54handling a request. In case there is no context available, then `context.Background()`
55can be used as a starting point.
56
57For more sample code snippets, head over to the
58[example](https://github.com/google/go-github/tree/master/example) directory.
59
60### Authentication ###
61
62The go-github library does not directly handle authentication. Instead, when
63creating a new client, pass an `http.Client` that can handle authentication for
64you. The easiest and recommended way to do this is using the [oauth2][]
65library, 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
67API token][]), you can use it with the oauth2 library using:
68
69```go
70import "golang.org/x/oauth2"
71
72func 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
86Note that when using an authenticated Client, all calls made by the client will
87include the specified OAuth token. Therefore, authenticated clients should
88almost never be shared between different users.
89
90See the [oauth2 docs][] for complete instructions on using that library.
91
92For API methods that require HTTP Basic Authentication, use the
93[`BasicAuthTransport`](https://godoc.org/github.com/google/go-github/github#BasicAuthTransport).
94
95GitHub Apps authentication can be provided by the [ghinstallation](https://github.com/bradleyfalzon/ghinstallation)
96package.
97
98```go
99import "github.com/bradleyfalzon/ghinstallation"
100
101func 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
117GitHub imposes a rate limit on all API clients. Unauthenticated clients are
118limited to 60 requests per hour, while authenticated clients can make up to
1195,000 requests per hour. The Search API has a custom rate limit. Unauthenticated
120clients are limited to 10 requests per minute, while authenticated clients
121can make up to 30 requests per minute. To receive the higher rate limit when
122making calls that are not issued on behalf of a user,
123use `UnauthenticatedRateLimitedTransport`.
124
125The returned `Response.Rate` value contains the rate limit information
126from the most recent API call. If a recent enough response isn't
127available, you can use `RateLimits` to fetch the most up-to-date rate
128limit data for the client.
129
130To detect an API rate limit error, you can check if its type is `*github.RateLimitError`:
131
132```go
133repos, _, err := client.Repositories.List(ctx, "", nil)
134if _, ok := err.(*github.RateLimitError); ok {
135	log.Println("hit rate limit")
136}
137```
138
139Learn more about GitHub rate limiting at
140https://docs.github.com/en/free-pro-team@latest/rest/reference/rate-limit.
141
142### Accepted Status ###
143
144Some endpoints may return a 202 Accepted status code, meaning that the
145information required is not yet ready and was scheduled to be gathered on
146the GitHub side. Methods known to behave like this are documented specifying
147this behavior.
148
149To detect this condition of error, you can check if its type is
150`*github.AcceptedError`:
151
152```go
153stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo)
154if _, ok := err.(*github.AcceptedError); ok {
155	log.Println("scheduled on GitHub side")
156}
157```
158
159### Conditional Requests ###
160
161The GitHub API has good support for conditional requests which will help
162prevent you from burning through your rate limit, as well as help speed up your
163application. `go-github` does not handle conditional requests directly, but is
164instead designed to work with a caching `http.Transport`. We recommend using
165https://github.com/gregjones/httpcache for that.
166
167Learn more about GitHub conditional requests at
168https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#conditional-requests.
169
170### Creating and Updating Resources ###
171
172All structs for GitHub resources use pointer values for all non-repeated fields.
173This allows distinguishing between unset fields and those set to a zero-value.
174Helper functions have been provided to easily create these pointers for string,
175bool, and int values. For example:
176
177```go
178// create a new private repository named "foo"
179repo := &github.Repository{
180	Name:    github.String("foo"),
181	Private: github.Bool(true),
182}
183client.Repositories.Create(ctx, "", repo)
184```
185
186Users who have worked with protocol buffers should find this pattern familiar.
187
188### Pagination ###
189
190All requests for resource collections (repos, pull requests, issues, etc.)
191support pagination. Pagination options are described in the
192`github.ListOptions` struct and passed to the list methods directly or as an
193embedded 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
198client := github.NewClient(nil)
199
200opt := &github.RepositoryListByOrgOptions{
201	ListOptions: github.ListOptions{PerPage: 10},
202}
203// get all pages of results
204var allRepos []*github.Repository
205for {
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
218For 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
230You can run integration tests from the `test` directory. See the integration tests [README](test/README.md).
231
232## Roadmap ##
233
234This library is being initially developed for an internal application at
235Google, so API methods will likely be implemented in the order that they are
236needed 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 ##
242I would like to cover the entire GitHub API and contributions are of course always welcome. The
243calling pattern is pretty well established, so adding new methods is relatively
244straightforward. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for details.
245
246## Versioning ##
247
248In general, go-github follows [semver](https://semver.org/) as closely as we
249can for tagging releases of the package. For self-contained libraries, the
250application of semantic versioning is relatively straightforward and generally
251understood. But because go-github is a client library for the GitHub API, which
252itself changes behavior, and because we are typically pretty aggressive about
253implementing preview features of the GitHub API, we've adopted the following
254versioning 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
265Preview functionality may take the form of entire methods or simply additional
266data returned from an otherwise non-preview method. Refer to the GitHub API
267documentation for details on preview functionality.
268
269## License ##
270
271This library is distributed under the BSD-style license found in the [LICENSE](./LICENSE)
272file.
273