Name: octokit.rb
Owner: Libraries.io
Description: Ruby toolkit for the GitHub API
Forked from: octokit/octokit.rb
Created: 2016-11-08 09:06:23.0
Updated: 2016-11-08 09:06:32.0
Pushed: 2016-11-09 09:25:15.0
Homepage: http://octokit.github.io/octokit.rb/
Size: 12390
Language: Ruby
GitHub Committers
User | Most Recent Commit | # Commits |
---|
Other Committers
User | Most Recent Commit | # Commits |
---|
Ruby toolkit for the GitHub API.
Upgrading? Check the Upgrade Guide before bumping to a new major version.
API wrappers should reflect the idioms of the language in which they were written. Octokit.rb wraps the GitHub API in a flat API client that follows Ruby conventions and requires little knowledge of REST. Most methods have positional arguments for required input and an options hash for optional parameters, headers, or other options:
tch a README with Accept header for HTML format
kit.readme 'al3x/sovereign', :accept => 'application/vnd.github.html'
Install via Rubygems
gem install octokit
… or add to your Gemfile
gem "octokit", "~> 4.0"
API methods are available as module methods (consuming module-level configuration) or as client instance methods.
ovide authentication credentials
kit.configure do |c|
login = 'defunkt'
password = 'c0d3b4ssssss!'
tch the current user
kit.user
or
ovide authentication credentials
nt = Octokit::Client.new(:login => 'defunkt', :password => 'c0d3b4ssssss!')
tch the current user
nt.user
Most methods return a Resource
object which provides dot notation and []
access for fields returned in the API response.
tch a user
= Octokit.user 'jbarnette'
user.name
"John Barnette"
user.fields
<Set: {:login, :id, :gravatar_id, :type, :name, :company, :blog, :location, :email, :hireable, :bio, :public_repos, :followers, :following, :created_at, :updated_at, :public_gists}>
user[:company]
"GitHub"
.rels[:gists].href
"https://api.github.com/users/jbarnette/gists"
Note: URL fields are culled into a separate .rels
collection for easier
Hypermedia support.
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
:
= Octokit.user 'andrewpthorp'
onse = Octokit.last_response
= response.headers[:etag]
Octokit supports the various authentication methods supported by the GitHub API:
Using your GitHub username and password is the easiest way to get started making authenticated requests:
nt = Octokit::Client.new \
ogin => 'defunkt',
assword => 'c0d3b4ssssss!'
= client.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 provide two main benefits over using your username and password:
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:
nt = Octokit::Client.new(:access_token => "<your 40 char token>")
= client.user
.login
"defunkt"
You can create access tokens through your GitHub Account Settings or with a basic authenticated Octokit client:
nt = Octokit::Client.new \
ogin => 'defunkt',
assword => 'c0d3b4ssssss!'
nt.create_authorization(:scopes => ["user"], :note => "Name of token")
<your new oauth token>
Two-Factor Authentication brings added security to the account by requiring more information to login.
Using two-factor authentication for API calls is as simple as adding the required header as an option:
nt = Octokit::Client.new \
ogin => 'defunkt',
assword => 'c0d3b4ssssss!'
= 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:
nt = Octokit::Client.new \
ogin => 'defunkt',
assword => 'c0d3b4ssssss!'
nt.create_authorization(:scopes => ["user"], :note => "Name of token",
:headers => { "X-GitHub-OTP" => "<your 2FA token>" })
<your new oauth token>
Octokit supports reading credentials from a netrc file (defaulting to
~/.netrc
). Given these lines in your netrc:
ine api.github.com
gin defunkt
ssword c0d3b4ssssss!
You can now create a client with those credentials:
nt = Octokit::Client.new(:netrc => true)
nt.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:
ine api.github.com
gin defunkt
ssword <your 40 char token>
Note: Support for netrc requires adding the netrc gem to your Gemfile
or .gemspec
.
Octokit also supports application-only authentication using OAuth application client credentials. Using application credentials will result in making anonymous API calls on behalf of an application in order to take advantage of the higher rate limit.
nt = Octokit::Client.new \
lient_id => "<your 20 char id>",
lient_secret => "<your 40 char secret>"
= client.user 'defunkt'
Many GitHub API resources are paginated. While you may be tempted to start
adding :page
parameters to your calls, the API returns links to the next,
previous, and last pages for you in the Link
response header as Hypermedia link relations.
es = Octokit.issues 'rails/rails', :per_page => 100
es.concat Octokit.last_response.rels[:next].get.data
For smallish resource lists, Octokit provides auto pagination. When this is enabled, calls for paginated resources will fetch and concatenate the results from every page into a single array:
kit.auto_paginate = true
es = Octokit.issues 'rails/rails'
es.length
702
Note: While Octokit auto pagination will set the page size to the maximum
100
, and seek to not overstep your rate limit, you probably want to use a
custom pattern for traversing large lists.
With a bit of setup, you can also use Octokit with your Github Enterprise instance.
To interact with the “regular” GitHub.com APIs in GitHub Enterprise, simply configure the api_endpoint
to match your hostname. For example:
kit.configure do |c|
api_endpoint = "https://<hostname>/api/v3/"
nt = Octokit::Client.new(:access_token => "<your 40 char token>")
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.
n_client = Octokit::EnterpriseAdminClient.new \
:access_token => "<your 40 char token>",
:api_endpoint => "https://<hostname>/api/v3/"
kit.configure do |c|
api_endpoint = "https://<hostname>/api/v3/"
access_token = "<your 40 char token>"
n_client = Octokit.enterprise_admin_client
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.
gement_console_client = Octokit::EnterpriseManagementConsoleClient.new \
:management_console_password => "secret",
:management_console_endpoint = "https://hostname:8633"
kit.configure do |c|
management_console_endpoint = "https://hostname:8633"
management_console_password = "secret"
gement_console_client = Octokit.enterprise_management_console_client
You may need to disable SSL temporarily while first setting up your GitHub Enterprise install. You can do that with the following configuration:
nt.connection_options[:ssl] = { :verify => false }
Do remember to turn :verify
back to true
, as it's important for secure communication.
While Octokit::Client
accepts a range of options when creating a new client
instance, Octokit's configuration API allows you to set your configuration
options at the module level. This is particularly handy if you're creating a
number of client instances based on some shared defaults. Changing options
affects new instances only and will not modify existing Octokit::Client
instances created with previous options.
Every writable attribute in {Octokit::Configurable} can be set one at a time:
kit.api_endpoint = 'http://api.github.dev'
kit.web_endpoint = 'http://github.dev'
or in batch:
kit.configure do |c|
api_endpoint = 'http://api.github.dev'
web_endpoint = 'http://github.dev'
Default configuration values are specified in {Octokit::Default}. Many attributes will look for a default value from the ENV before returning Octokit's default.
ven $OCTOKIT_API_ENDPOINT is "http://api.github.dev"
kit.api_endpoint
"http://api.github.dev"
Deprecation warnings and API endpoints in development preview warnings are
printed to STDOUT by default, these can be disabled by setting the ENV
OCTOKIT_SILENT=true
.
Starting in version 2.0, Octokit is hypermedia-enabled. Under the hood, {Octokit::Client} uses Sawyer, a hypermedia client built on Faraday.
Resources returned by Octokit methods contain not only data but hypermedia link relations:
= Octokit.user 'technoweenie'
t the repos rel, returned from the API
repos_url in the resource
.rels[:repos].href
"https://api.github.com/users/technoweenie/repos"
s = user.rels[:repos].get.data
s.last.name
"faraday-zeromq"
When processing API responses, all *_url
attributes are culled in to the link
relations collection. Any url
attribute becomes .rels[:self]
.
You might notice many link relations have variable placeholders. Octokit supports URI Templates for parameterized URI expansion:
= Octokit.repo 'pengwynn/pingwynn'
= repo.rels[:issues]
#<Sawyer::Relation: issues: get https://api.github.com/repos/pengwynn/pingwynn/issues{/number}>
t a page of issues
get.data
t issue #2
get(:uri => {:number => 2}).data
If you want to use Octokit as a pure hypermedia API client, you can start at the API root and follow link relations from there:
= Octokit.root
.rels[:repository].get :uri => {:owner => "octokit", :repo => "octokit.rb" }
.rels[:user_repositories].get :uri => { :user => "octokit" },
:query => { :type => "owner" }
Octokit 3.0 aims to be hypermedia-driven, removing the internal URL construction currently used throughout the client.
Version 4.0
state
in the method options.Version 3.0 includes a couple breaking changes when upgrading from v2.x.x:
The default media type is now v3
instead of beta
. If
you need to request the older media type, you can set the default media type
for the client:
kit.default_media_type = "application/vnd.github.beta+json"
or per-request
kit.emails(:accept => "application/vnd.github.beta+json")
The long-deprecated Octokit::Client#create_download
method has been removed.
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
object. This new type behaves mostly like a Ruby Hash
, but does not fully
support the Hashie::Mash
API.Octokit::TooManyRequests
and Octokit::TooManyLoginAttempts
search_*
methods from v1.x are now found at legacy_search_*
DateTime
objects. Previous versions outputted DateTime fields as 'String' objects.Since Octokit employs Faraday under the hood, some behavior can be extended via middleware.
Often, it helps to know what Octokit is doing under the hood. You can add a logger to the middleware that enables you to peek into the underlying HTTP traffic:
k = Faraday::RackBuilder.new do |builder|
ilder.response :logger
ilder.use Octokit::Response::RaiseError
ilder.adapter Faraday.default_adapter
kit.middleware = stack
kit.user 'pengwynn'
2013-08-22T15:54:38.583300 #88227] INFO -- : get https://api.github.com/users/pengwynn
2013-08-22T15:54:38.583401 #88227] DEBUG -- request: Accept: "application/vnd.github.beta+json"
-Agent: "Octokit Ruby Gem 2.0.0.rc4"
2013-08-22T15:54:38.843313 #88227] INFO -- Status: 200
2013-08-22T15:54:38.843459 #88227] DEBUG -- response: server: "GitHub.com"
: "Thu, 22 Aug 2013 20:54:40 GMT"
ent-type: "application/json; charset=utf-8"
sfer-encoding: "chunked"
ection: "close"
us: "200 OK"
telimit-limit: "60"
telimit-remaining: "39"
telimit-reset: "1377205443"
See the Faraday README for more middleware magic.
If you want to boost performance, stretch your API rate limit, or avoid paying the hypermedia tax, you can use Faraday Http Cache.
Add the gem to your Gemfile
gem 'faraday-http-cache'
Next, construct your own Faraday middleware:
k = Faraday::RackBuilder.new do |builder|
ilder.use Faraday::HttpCache, serializer: Marshal, shared_cache: false
ilder.use Octokit::Response::RaiseError
ilder.adapter Faraday.default_adapter
kit.middleware = stack
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 for advanced usage.
If you want to hack on Octokit locally, we try to make bootstrapping the project as painless as possible. To start hacking, clone and run:
script/bootstrap
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 ./scripts
instead of bundle exec rspec
, bundle
console
, etc. ensures your dependencies are up-to-date.
Octokit uses VCR for recording and playing back API fixtures during test
runs. These cassettes (fixtures) are part of the Git project in the spec/cassettes
folder. If you're not recording new cassettes you can run the specs with existing
cassettes with:
script/test
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.
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 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
Since we periodically refresh our cassettes, please keep some points in mind when writing new specs.
This library aims to support and is tested against the following Ruby implementations:
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 above.
If you would like this library to support another Ruby version, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped.
This library aims to adhere to Semantic Versioning 2.0.0. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, that version should be immediately yanked and/or a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions. As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision. For example:
spec.add_dependency 'octokit', '~> 3.0'
The changes made between versions can be seen on the project releases page.
Copyright (c) 2009-2014 Wynn Netherland, Adam Stacoviak, Erik Michaels-Ober
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.