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 # =>

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

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

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多