README.md in octokit-4.22.0 vs README.md in octokit-4.23.0

- old
+ new

@@ -8,27 +8,29 @@ [major version][semver]. ## Table of Contents 1. [Philosophy](#philosophy) -2. [Quick start](#quick-start) +2. [Installation](#quick-start) 3. [Making requests](#making-requests) + 1. [Additional Query Parameters](#additional-query-parameters) 4. [Consuming resources](#consuming-resources) 5. [Accessing HTTP responses](#accessing-http-responses) -6. [Authentication](#authentication) +6. [Handling errors](#handling-errors) +7. [Authentication](#authentication) 1. [Basic Authentication](#basic-authentication) 2. [OAuth access tokens](#oauth-access-tokens) 3. [Two-Factor Authentication](#two-factor-authentication) 4. [Using a .netrc file](#using-a-netrc-file) 5. [Application authentication](#application-authentication) -7. [Pagination](#pagination) +8. [Pagination](#pagination) 1. [Auto pagination](#auto-pagination) -8. [Working with GitHub Enterprise](#working-with-github-enterprise) +9. [Working with GitHub Enterprise](#working-with-github-enterprise) 1. [Interacting with the GitHub.com APIs in GitHub Enterprise](#interacting-with-the-githubcom-apis-in-github-enterprise) 2. [Interacting with the GitHub Enterprise Admin APIs](#interacting-with-the-github-enterprise-admin-apis) 3. [Interacting with the GitHub Enterprise Management Console APIs](#interacting-with-the-github-enterprise-management-console-apis) -9. [SSL Connection Errors](#ssl-connection-errors) + 4. [SSL Connection Errors](#ssl-connection-errors) 10. [Configuration and defaults](#configuration-and-defaults) 1. [Configuring module defaults](#configuring-module-defaults) 2. [Using ENV variables](#using-env-variables) 3. [Timeouts](#timeouts) 11. [Hypermedia agent](#hypermedia-agent) @@ -64,11 +66,11 @@ ``` [wrappers]: http://wynnnetherland.com/journal/what-makes-a-good-api-wrapper [github-api]: https://developer.github.com/v3/ -## Quick start +## Installation Install via Rubygems gem install octokit @@ -78,11 +80,11 @@ Access the library in Ruby: require 'octokit' -### Making requests +## Making requests [API methods][] are available as client instance methods. ```ruby # Provide authentication credentials @@ -93,11 +95,11 @@ # Fetch the current user client.user ``` -### Additional Query Parameters +### Additional query parameters When passing additional parameters to GET based request use the following syntax: ```ruby # query: { parameter_name: 'value' } @@ -107,13 +109,13 @@ # Example: Get contents of a repository by ref # https://api.github.com/repos/octokit/octokit.rb/contents/path/to/file.rb?ref=some-other-branch client.contents('octokit/octokit.rb', path: 'path/to/file.rb', query: {ref: 'some-other-branch'}) ``` -[API methods]: http://octokit.github.io/octokit.rb/method_list.html +[api methods]: http://octokit.github.io/octokit.rb/method_list.html -### Consuming resources +## Consuming resources Most methods return a `Resource` object which provides dot notation and `[]` access for fields returned in the API response. ```ruby @@ -132,11 +134,11 @@ ``` **Note:** URL fields are culled into a separate `.rels` collection for easier [Hypermedia](#hypermedia-agent) support. -### Accessing HTTP responses +## Accessing HTTP responses While most methods return a `Resource` object or a Boolean, sometimes you may need access to the raw HTTP response headers. You can access the last HTTP response with `Client#last_response`: @@ -144,10 +146,27 @@ user = client.user 'andrewpthorp' response = client.last_response etag = response.headers[:etag] ``` +## Handling errors + +When the API returns an error response, Octokit will raise a Ruby exception. + +A range of different exceptions can be raised depending on the error returned +by the API - for example: + +* A `400 Bad Request` response will lead to an `Octokit::BadRequest` error +* A `403 Forbidden` error with a "rate limited exceeded" message will lead + to a `Octokit::TooManyRequests` error + +All of the different exception classes inherit from `Octokit::Error` and +expose the `#response_status`, `#response_headers` and `#response_body`. +For validation errors, `#errors` will return an `Array` of `Hash`es +with the detailed information +[returned by the API](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#client-errors). + ## Authentication Octokit supports the various [authentication methods supported by the GitHub API][auth]: @@ -161,21 +180,22 @@ user = client.user user.login # => "defunkt" ``` + While Basic Authentication allows you to get started quickly, OAuth access tokens are the preferred way to authenticate on behalf of users. ### OAuth access tokens [OAuth access tokens][oauth] provide two main benefits over using your username and password: -* **Revokable access**. Access tokens can be revoked, removing access for only +- **Revocable access**. Access tokens can be revoked, removing access for only that token without having to change your password everywhere. -* **Limited access**. Access tokens have [access scopes][] which allow for more +- **Limited access**. Access tokens have [access scopes][] which allow for more granular access to API resources. For instance, you can grant a third party access to your gists but not your private repositories. To use an access token with the Octokit client, pass your token in the `:access_token` options parameter in lieu of your username and password: @@ -210,11 +230,11 @@ :password => 'c0d3b4ssssss!' user = client.user("defunkt", :headers => { "X-GitHub-OTP" => "<your 2FA token>" }) ``` -As you can imagine, this gets annoying quick since two-factor auth tokens are very short lived. So it is recommended to create an oauth token for the user to communicate with the API: +As you can imagine, this gets annoying quickly since two-factor auth tokens are very short lived. So it is recommended to create an oauth token for the user to communicate with the API: ```ruby client = Octokit::Client.new \ :login => 'defunkt', :password => 'c0d3b4ssssss!' @@ -225,24 +245,26 @@ ``` ### Using a .netrc file Octokit supports reading credentials from a netrc file (defaulting to -`~/.netrc`). Given these lines in your netrc: +`~/.netrc`). Given these lines in your netrc: ``` machine api.github.com login defunkt password c0d3b4ssssss! ``` + You can now create a client with those credentials: ```ruby client = Octokit::Client.new(:netrc => true) client.login # => "defunkt" ``` + But _I want to use OAuth_ you say. Since the GitHub API supports using an OAuth token as a Basic password, you totally can: ``` machine api.github.com @@ -327,11 +349,11 @@ ### Interacting with the GitHub.com APIs in GitHub Enterprise To interact with the "regular" GitHub.com APIs in GitHub Enterprise, simply configure the `api_endpoint` to match your hostname. For example: -``` ruby +```ruby Octokit.configure do |c| c.api_endpoint = "https://<hostname>/api/v3/" end client = Octokit::Client.new(:access_token => "<your 40 char token>") @@ -339,11 +361,11 @@ ### Interacting with the GitHub Enterprise Admin APIs The GitHub Enterprise Admin APIs are under a different client: `EnterpriseAdminClient`. You'll need to have an administrator account in order to use these APIs. -``` ruby +```ruby admin_client = Octokit::EnterpriseAdminClient.new( :access_token => "<your 40 char token>", :api_endpoint => "https://<hostname>/api/v3/" ) @@ -356,13 +378,13 @@ admin_client = Octokit.enterprise_admin_client.new ``` ### Interacting with the GitHub Enterprise Management Console APIs -The GitHub Enterprise Management Console APIs are also under a separate client: `EnterpriseManagementConsoleClient`. In order to use it, you'll need to provide both your management console password as well as the endpoint to your management console. This is different than the API endpoint provided above. +The GitHub Enterprise Management Console APIs are also under a separate client: `EnterpriseManagementConsoleClient`. In order to use it, you'll need to provide both your management console password as well as the endpoint to your management console. This is different from the API endpoint provided above. -``` ruby +```ruby management_console_client = Octokit::EnterpriseManagementConsoleClient.new( :management_console_password => "secret", :management_console_endpoint = "https://hostname:8633" ) @@ -375,13 +397,13 @@ management_console_client = Octokit.enterprise_management_console_client.new ``` ### SSL Connection Errors -You *may* need to disable SSL temporarily while first setting up your GitHub Enterprise install. You can do that with the following configuration: +You _may_ need to disable SSL temporarily while first setting up your GitHub Enterprise install. You can do that with the following configuration: -``` ruby +```ruby client.connection_options[:ssl] = { :verify => false } ``` Do remember to turn `:verify` back to `true`, as it's important for secure communication. @@ -442,10 +464,11 @@ timeout: 5 } } end ``` + You should set a timeout in order to avoid Ruby’s Timeout module, which can hose your server. Here are some resources for more information on this: - [The Oldest Bug In Ruby - Why Rack::Timeout Might Hose your Server](https://www.schneems.com/2017/02/21/the-oldest-bug-in-ruby-why-racktimeout-might-hose-your-server/) - [Timeout: Ruby's Most Dangerous API](https://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/) - [The Ultimate Guide to Ruby Timeouts](https://github.com/ankane/the-ultimate-guide-to-ruby-timeouts) @@ -471,11 +494,11 @@ repos = user.rels[:repos].get.data repos.last.name # => "faraday-zeromq" ``` -When processing API responses, all `*_url` attributes are culled in to the link +When processing API responses, all `*_url` attributes are culled into the link relations collection. Any `url` attribute becomes `.rels[:self]`. ### URI templates You might notice many link relations have variable placeholders. Octokit @@ -507,21 +530,21 @@ Octokit 3.0 aims to be hypermedia-driven, removing the internal URL construction currently used throughout the client. [hypermedia]: http://en.wikipedia.org/wiki/Hypermedia -[Sawyer]: https://github.com/lostisland/sawyer -[Faraday]: https://github.com/lostisland/faraday +[sawyer]: https://github.com/lostisland/sawyer +[faraday]: https://github.com/lostisland/faraday [uri-templates]: http://tools.ietf.org/html/rfc6570 ## Upgrading guide Version 4.0 - **removes support for a [long-deprecated overload][list-pulls] for -passing state as a positional argument** when listing pull requests. Instead, -pass `state` in the method options. + passing state as a positional argument** when listing pull requests. Instead, + pass `state` in the method options. - **drops support for Ruby < 2.0**. - adds support for new [Enterprise-only APIs](#working-with-github-enterprise). - adds support for [Repository redirects][redirects]. [list-pulls]: https://github.com/octokit/octokit.rb/commit/e48e91f736d5fce51e3bf74d7c9022aaa52f5c5c @@ -534,10 +557,11 @@ for the client: ```ruby Octokit.default_media_type = "application/vnd.github.beta+json" ``` + or per-request ```ruby client.emails(:accept => "application/vnd.github.beta+json") ``` @@ -550,25 +574,24 @@ Version 2.0 includes a completely rewritten `Client` factory that now memoizes client instances based on unique configuration options. Breaking changes also include: -* `:oauth_token` is now `:access_token` -* `:auto_traversal` is now `:auto_paginate` -* `Hashie::Mash` has been removed. Responses now return a `Sawyer::Resource` +- `:oauth_token` is now `:access_token` +- `:auto_traversal` is now `:auto_paginate` +- `Hashie::Mash` has been removed. Responses now return a `Sawyer::Resource` object. This new type behaves mostly like a Ruby `Hash`, but does not fully support the `Hashie::Mash` API. -* Two new client error types are raised where appropriate: +- Two new client error types are raised where appropriate: `Octokit::TooManyRequests` and `Octokit::TooManyLoginAttempts` -* The `search_*` methods from v1.x are now found at `legacy_search_*` -* Support for netrc requires including the [netrc gem][] in your Gemfile or +- The `search_*` methods from v1.x are now found at `legacy_search_*` +- Support for netrc requires including the [netrc gem][] in your Gemfile or gemspec. -* DateTime fields are now proper `DateTime` objects. Previous versions outputted DateTime fields as 'String' objects. +- DateTime fields are now proper `DateTime` objects. Previous versions outputted DateTime fields as 'String' objects. [netrc gem]: https://rubygems.org/gems/netrc - ## Advanced usage Since Octokit employs [Faraday][faraday] under the hood, some behavior can be extended via middleware. @@ -578,11 +601,11 @@ logger to the middleware that enables you to peek into the underlying HTTP traffic: ```ruby stack = Faraday::RackBuilder.new do |builder| - builder.use Faraday::Request::Retry, exceptions: [Octokit::ServerError] + builder.use Faraday::Retry::Middleware, exceptions: [Octokit::ServerError] # or Faraday::Request::Retry for Faraday < 2.0 builder.use Octokit::Middleware::FollowRedirects builder.use Octokit::Response::RaiseError builder.use Octokit::Response::FeedParser builder.response :logger do |logger| logger.filter(/(Authorization: "(token|Bearer) )(\w+)/, '\1[REMOVED]') @@ -592,10 +615,11 @@ Octokit.middleware = stack client = Octokit::Client.new client.user 'pengwynn' ``` + ``` I, [2013-08-22T15:54:38.583300 #88227] INFO -- : get https://api.github.com/users/pengwynn D, [2013-08-22T15:54:38.583401 #88227] DEBUG -- request: Accept: "application/vnd.github.beta+json" User-Agent: "Octokit Ruby Gem 2.0.0.rc4" I, [2013-08-22T15:54:38.843313 #88227] INFO -- Status: 200 @@ -635,11 +659,10 @@ Once configured, the middleware will store responses in cache based on ETag fingerprint and serve those back up for future `304` responses for the same resource. See the [project README][cache] for advanced usage. - [cache]: https://github.com/plataformatec/faraday-http-cache [faraday]: https://github.com/lostisland/faraday ## Hacking on Octokit.rb @@ -651,16 +674,15 @@ This will install project dependencies and get you up and running. If you want to run a Ruby console to poke on Octokit, you can crank one up with: script/console -Using the scripts in `./script` instead of `bundle exec rspec`, `bundle -console`, etc. ensures your dependencies are up-to-date. +Using the scripts in `./script` instead of `bundle exec rspec`, `bundle console`, etc. ensures your dependencies are up-to-date. ### Code of Conduct -We want both the Octokit.rb and larger Octokit communities to be an open +We want both the Octokit.rb and larger Octokit communities to be open and welcoming environments. Please read and follow both in spirit and letter [Code of Conduct](CODE_OF_CONDUCT.md). ### Running and writing new tests @@ -673,56 +695,58 @@ Octokit uses environmental variables for storing credentials used in testing. If you are testing an API endpoint that doesn't require authentication, you can get away without any additional configuration. For the most part, tests use an authenticated client, using a token stored in `ENV['OCTOKIT_TEST_GITHUB_TOKEN']`. -There are several different authenticating method's used across the api. +There are several different authentication methods used across the api. Here is the full list of configurable environmental variables for testing Octokit: -ENV Variable | Description | -:-------------------|:-----------------| -`OCTOKIT_TEST_GITHUB_LOGIN`| GitHub login name (preferably one created specifically for testing against). -`OCTOKIT_TEST_GITHUB_PASSWORD`| Password for the test GitHub login. -`OCTOKIT_TEST_GITHUB_TOKEN` | [Personal Access Token](https://github.com/blog/1509-personal-api-tokens) for the test GitHub login. -`OCTOKIT_TEST_GITHUB_CLIENT_ID` | Test OAuth application client id. -`OCTOKIT_TEST_GITHUB_CLIENT_SECRET` | Test OAuth application client secret. -`OCTOKIT_TEST_GITHUB_REPOSITORY` | Test repository to perform destructive actions against, this should not be set to any repository of importance. **Automatically created by the test suite if nonexistent** Default: `api-sandbox` -`OCTOKIT_TEST_GITHUB_ORGANIZATION` | Test organization. -`OCTOKIT_TEST_GITHUB_ENTERPRISE_LOGIN` | GitHub Enterprise login name. -`OCTOKIT_TEST_GITHUB_ENTERPRISE_TOKEN` | GitHub Enterprise token. -`OCTOKIT_TEST_GITHUB_ENTERPRISE_MANAGEMENT_CONSOLE_PASSWORD` | GitHub Enterprise management console password. -`OCTOKIT_TEST_GITHUB_ENTERPRISE_ENDPOINT` | GitHub Enterprise hostname. -`OCTOKIT_TEST_GITHUB_ENTERPRISE_MANAGEMENT_CONSOLE_ENDPOINT` | GitHub Enterprise Management Console endpoint. -`OCTOKIT_TEST_GITHUB_INTEGRATION` | [GitHub Integration](https://developer.github.com/early-access/integrations/) owned by your test organization. -`OCTOKIT_TEST_GITHUB_INTEGRATION_INSTALLATION` | Installation of the GitHub Integration specified above. -`OCTOKIT_TEST_INTEGRATION_PEM_KEY` | File path to the private key generated from your integration. +| ENV Variable | Description | +| :----------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `OCTOKIT_TEST_GITHUB_LOGIN` | GitHub login name (preferably one created specifically for testing against). | +| `OCTOKIT_TEST_GITHUB_PASSWORD` | Password for the test GitHub login. | +| `OCTOKIT_TEST_GITHUB_TOKEN` | [Personal Access Token](https://github.com/blog/1509-personal-api-tokens) for the test GitHub login. | +| `OCTOKIT_TEST_GITHUB_CLIENT_ID` | Test OAuth application client id. | +| `OCTOKIT_TEST_GITHUB_CLIENT_SECRET` | Test OAuth application client secret. | +| `OCTOKIT_TEST_GITHUB_REPOSITORY` | Test repository to perform destructive actions against, this should not be set to any repository of importance. **Automatically created by the test suite if nonexistent** Default: `api-sandbox` | +| `OCTOKIT_TEST_GITHUB_ORGANIZATION` | Test organization. | +| `OCTOKIT_TEST_GITHUB_ENTERPRISE_LOGIN` | GitHub Enterprise login name. | +| `OCTOKIT_TEST_GITHUB_ENTERPRISE_TOKEN` | GitHub Enterprise token. | +| `OCTOKIT_TEST_GITHUB_ENTERPRISE_MANAGEMENT_CONSOLE_PASSWORD` | GitHub Enterprise management console password. | +| `OCTOKIT_TEST_GITHUB_ENTERPRISE_ENDPOINT` | GitHub Enterprise hostname. | +| `OCTOKIT_TEST_GITHUB_ENTERPRISE_MANAGEMENT_CONSOLE_ENDPOINT` | GitHub Enterprise Management Console endpoint. | +| `OCTOKIT_TEST_GITHUB_INTEGRATION` | [GitHub Integration](https://developer.github.com/early-access/integrations/) owned by your test organization. | +| `OCTOKIT_TEST_GITHUB_INTEGRATION_INSTALLATION` | Installation of the GitHub Integration specified above. | +| `OCTOKIT_TEST_INTEGRATION_PEM_KEY` | File path to the private key generated from your integration. | Since we periodically refresh our cassettes, please keep some points in mind when writing new specs. -* **Specs should be idempotent**. The HTTP calls made during a spec should be +- **Specs should be idempotent**. The HTTP calls made during a spec should be able to be run over and over. This means deleting a known resource prior to creating it if the name has to be unique. -* **Specs should be able to be run in random order.** If a spec depends on +- **Specs should be able to be run in random order.** If a spec depends on another resource as a fixture, make sure that's created in the scope of the spec and not depend on a previous spec to create the data needed. -* **Do not depend on authenticated user info.** Instead of asserting +- **Do not depend on authenticated user info.** Instead of asserting actual values in resources, try to assert the existence of a key or that a response is an Array. We're testing the client, not the API. [bootstrapping]: http://wynnnetherland.com/linked/2013012801/bootstrapping-consistency -[VCR]: https://github.com/vcr/vcr +[vcr]: https://github.com/vcr/vcr ## Supported Ruby Versions This library aims to support and is [tested against][actions] the following Ruby implementations: * Ruby 2.5 * Ruby 2.6 * Ruby 2.7 +* Ruby 3.0 +* Ruby 3.1 If something doesn't work on one of these Ruby versions, it's a bug. This library may inadvertently work (or seem to work) on other Ruby implementations, but support will only be provided for the versions listed @@ -755,10 +779,11 @@ [semver]: http://semver.org/ [pvc]: http://guides.rubygems.org/patterns/#pessimistic-version-constraint [releases]: https://github.com/octokit/octokit.rb/releases ## Making Repeating Requests -In most cases it would be best to use a [webhooks](https://developer.github.com/webhooks/), but sometimes webhooks don't provide all of the information needed. In those cases where one might need to poll for progress or retry a request on failure, we designed [Octopoller](https://github.com/octokit/octopoller.rb). Octopoller is a micro gem perfect for making repeating requests. + +In most cases it would be best to use [webhooks](https://developer.github.com/webhooks/), but sometimes webhooks don't provide all of the information needed. In those cases where one might need to poll for progress or retry a request on failure, we designed [Octopoller](https://github.com/octokit/octopoller.rb). Octopoller is a micro gem perfect for making repeating requests. ```ruby Octopoller.poll(timeout: 15.seconds) do begin client.request_progress # ex. request a long running job's status