octokit.rb

octokit.rb

将GitHub API集成简化为Ruby工具包

Octokit.rb是GitHub API的Ruby客户端库。它封装了API调用,提供简洁接口访问用户、仓库、问题、Pull Request等GitHub功能。支持多种认证方式,包括OAuth令牌和应用程序认证。该库还实现了分页、缓存、自动重试等高级特性,简化了与GitHub集成的应用开发。Octokit.rb设计遵循Ruby惯例,API直观易用。

OctokitGitHub APIRuby认证分页Github开源项目

Octokit

Note We've recently renamed the 4-stable branch to main. This might affect you if you're making changes to Octokit's code locally. For more details and for the steps to reconfigure your local clone for the new branch name, check out this post.

Ruby toolkit for the GitHub API.

logo

Upgrading? Check the Upgrade Guide before bumping to a new [major version][semver].

Table of Contents

  1. Philosophy
  2. Installation
  3. Making requests
    1. Additional Query Parameters
  4. Consuming resources
  5. Accessing HTTP responses
  6. Handling errors
  7. Authentication
    1. Basic Authentication
    2. OAuth access tokens
    3. Two-Factor Authentication
    4. Using a .netrc file
    5. Application authentication
    6. GitHub App
  8. Default results per_page
  9. Pagination
    1. Auto pagination
  10. Working with GitHub Enterprise
  11. Interacting with the GitHub.com APIs in GitHub Enterprise
  12. Interacting with the GitHub Enterprise Admin APIs
  13. Interacting with the GitHub Enterprise Management Console APIs
  14. SSL Connection Errors
  15. Configuration and defaults
    1. Configuring module defaults
    2. Using ENV variables
    3. Timeouts
  16. Hypermedia agent
    1. Hypermedia in Octokit
    2. URI templates
    3. The Full Hypermedia Experience™
  17. Upgrading guide
    1. Upgrading from 1.x.x
  18. Advanced usage
    1. Debugging
    2. Caching
  19. Hacking on Octokit.rb
    1. Code of Conduct
    2. Running and writing new tests
  20. Supported Ruby Versions
  21. Versioning
  22. Making Repeating Requests
  23. License

Philosophy

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:

client = Octokit::Client.new # Fetch a README with Accept header for HTML format client.readme 'al3x/sovereign', :accept => 'application/vnd.github.html'

Installation

Install via Rubygems

gem install octokit

... or add to your Gemfile

gem "octokit"

Access the library in Ruby:

require 'octokit'

Making requests

API methods are available as client instance methods.

# Provide authentication credentials client = Octokit::Client.new(:access_token => 'personal_access_token') # You can still use the username/password syntax by replacing the password value with your PAT. # client = Octokit::Client.new(:login => 'defunkt', :password => 'personal_access_token') # Fetch the current user client.user

Additional query parameters

When passing additional parameters to GET based request use the following syntax:

# query: { parameter_name: 'value' } # Example: Get repository listing by owner in ascending order client.repos({}, query: {type: 'owner', sort: 'asc'}) # 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'})

Consuming resources

Most methods return a Resource object which provides dot notation and [] access for fields returned in the API response.

client = Octokit::Client.new # Fetch a user user = client.user 'jbarnette' puts user.name # => "John Barnette" puts 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}> puts user[:company] # => "GitHub" user.rels[:gists].href # => "https://api.github.com/users/jbarnette/gists"

Note: URL fields are culled into a separate .rels collection for easier Hypermedia support.

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:

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 Hashes with the detailed information returned by the API.

Authentication

Octokit supports the various authentication methods supported by the GitHub API:

Basic Authentication

Using your GitHub username and password is the easiest way to get started making authenticated requests:

client = Octokit::Client.new(:login => 'defunkt', :password => 'c0d3b4ssssss!') 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 provide two main benefits over using your username and password:

  • 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 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:

client = Octokit::Client.new(:access_token => "<your 40 char token>") user = client.user user.login # => "defunkt"

You can create access tokens through your GitHub Account Settings.

Two-Factor Authentication

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:

client = Octokit::Client.new \ :login => 'defunkt', :password => 'c0d3b4ssssss!' user = client.user("defunkt", :headers => { "X-GitHub-OTP" => "<your 2FA token>" })

Using a .netrc file

Octokit supports reading credentials from a netrc file (defaulting to ~/.netrc). Given these lines in your netrc:

machine api.github.com
  login defunkt
  password c0d3b4ssssss!

You can now create a client with those credentials:

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
  login defunkt
  password <your 40 char token>

Note: Support for netrc requires adding the [netrc gem][] to your Gemfile or .gemspec.

Application authentication

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.

client = Octokit::Client.new \ :client_id => "<your 20 char id>", :client_secret => "<your 40 char secret>" user = client.user 'defunkt'

GitHub App

Octokit.rb also supports authentication using a GitHub App, which requires a generated JWT token.

client = Octokit::Client.new(:bearer_token => "<your jwt token>") client.app # => about GitHub App info

Default results per_page

Default results from the GitHub API are 30, if you wish to add more you must do so during Octokit configuration.

Octokit::Client.new(access_token: "<your 40 char token>", per_page: 100)

Pagination

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.

issues = client.issues 'rails/rails' issues.concat client.get(client.last_response.rels[:next].href)

Auto pagination

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:

client.auto_paginate = true issues = client.issues 'rails/rails' issues.length # => 702

You can also enable auto pagination for all Octokit client instances:

Octokit.configure do |c| c.auto_paginate = true end

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.

Working with GitHub Enterprise

With a bit of setup, you can also use Octokit with your GitHub Enterprise instance.

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:

Octokit.configure do |c| c.api_endpoint = "https://<hostname>/api/v3/" end client = Octokit::Client.new(:access_token => "<your 40 char token>")

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.

admin_client = Octokit::EnterpriseAdminClient.new( :access_token => "<your 40 char token>", :api_endpoint => "https://<hostname>/api/v3/" ) # or Octokit.configure do |c| c.api_endpoint = "https://<hostname>/api/v3/" c.access_token = "<your 40 char token>" end 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 from the API endpoint provided above.

management_console_client = Octokit::EnterpriseManagementConsoleClient.new( :management_console_password => "secret", :management_console_endpoint = "https://hostname:8633" ) # or Octokit.configure do |c| c.management_console_endpoint = "https://hostname:8633" c.management_console_password = "secret" end 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:

client.connection_options[:ssl] = { :verify => false }

Do remember to turn :verify back to true, as it's important for secure communication.

Configuration and defaults

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.

Configuring module defaults

Every writable attribute in {Octokit::Configurable} can be set one at a time:

Octokit.api_endpoint = 'http://api.github.dev' Octokit.web_endpoint = 'http://github.dev'

or in batch:

Octokit.configure do |c| c.api_endpoint = 'http://api.github.dev' c.web_endpoint = 'http://github.dev' end

Using ENV variables

Default configuration values are specified in {Octokit::Default}. Many attributes will look for a default value from the ENV before returning Octokit's default.

# Given $OCTOKIT_API_ENDPOINT is "http://api.github.dev" client.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.

Timeouts

By default, Octokit does not timeout network requests. To set a timeout, pass in Faraday timeout settings to Octokit's connection_options setting.

Octokit.configure do |c| c.api_endpoint = ENV.fetch('GITHUB_API_ENDPOINT', 'https://api.github.com/') c.connection_options = { request: { open_timeout: 5, 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:

Hypermedia agent

Starting in version 2.0, Octokit is [hypermedia][]-enabled. Under the hood, {Octokit::Client} uses [Sawyer][], a hypermedia client built on [Faraday][].

Hypermedia in Octokit

Resources returned by Octokit methods contain not only data but hypermedia link relations:

user = client.user 'technoweenie' # Get the repos rel, returned from the API # as repos_url in the resource user.rels[:repos].href # =>

编辑推荐精选

扣子-AI办公

扣子-AI办公

职场AI,就用扣子

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

堆友

堆友

多风格AI绘画神器

堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。

Vora

Vora

免费创建高清无水印Sora视频

Vora是一个免费创建高清无水印Sora视频的AI工具

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

下拉加载更多