Octokit.rb Documentation

repository·main·Indexed 26 days ago

https://github.com/octokit/octokit.rb

A Ruby toolkit for interacting with the GitHub API. It provides a flat, idiomatic Ruby interface that wraps RESTful calls into method calls. Features include support for OAuth, Basic Authentication, GitHub Apps, and GitHub Enterprise (including EnterpriseAdminClient and ManageGHESClient). It supports Ruby versions 2.7 through 3.3 and provides utilities for auto-pagination, hypermedia navigation via Sawyer, and custom Faraday middleware for caching and logging.

Tokens
11.4K
Snippets
48
Records
98
Agent score
87%

What's inside Octokit.rb

  1. Configure Octokit for GitHub Enterprise

    main

    To use Octokit with a GitHub Enterprise instance, you must configure the api_endpoint.

    Interacting with GitHub.com APIs in GitHub Enterprise

    Set the api_endpoint to your enterprise hostname's API path (e.g., https://<hostname>/api/v3/).

    Interacting with GitHub Enterprise Admin APIs

    Use the Octokit::EnterpriseAdminClient for administrator APIs. You can instantiate it directly or configure module-level defaults.

    Interacting with the GHES Manage API

    Use the Octokit::ManageGHESClient for the GitHub Enterprise Server (GHES) Manage API. This requires a manage_ghes_endpoint (which differs from the standard API endpoint), a manage_ghes_username, and a manage_ghes_password).

    # GitHub Enterprise standard API
    Octokit.configure do |c|
      c.api_endpoint = "https://<hostname>/api/v3/"
    end
    client = Octokit::Client.new(:access_token => "<your 40 char token>")
    
    # GitHub Enterprise Admin API
    admin_client = Octokit::EnterpriseAdminClient.new(
      :access_token => "<your 40 char token>",
      :api_endpoint => "https://<hostname>/api/v3/"
    )
    
    # GHES Manage API
    ghes_client = Octokit::ManageGHESClient.new(
      :manage_ghes_endpoint => "https://hostname:8443",
      :manage_ghes_username => "username",
      :manage_ghes_password => "password"
    )
  2. Debug Octokit HTTP traffic

    main

    Since Octokit uses Faraday, you can inject a logger into the middleware stack to inspect underlying HTTP requests and responses. This is useful for debugging authentication or payload issues.

    stack = Faraday::RackBuilder.new do |builder|
      builder.use Faraday::Retry::Middleware, exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [Octokit::ServerError]
      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]')
      end
      builder.adapter Faraday.default_adapter
    end
    Octokit.middleware = stack
    
    client = Octokit::Client.new
    client.user 'pengwynn'
  3. Bootstrap Octokit.rb for local development

    main

    To set up a local development environment for hacking on Octokit.rb, use the provided bootstrap script to install dependencies and prepare the project.

    To bootstrap the project:

    script/bootstrap

    To open a Ruby console to interact with Octokit locally:

    script/console

    Using the scripts in ./script ensures that your dependencies are up-to-date compared to running bundle exec commands directly.

    script/bootstrap
  4. Implement Caching with Faraday Http Cache

    main

    To improve performance and respect rate limits, you can add faraday-http-cache to your middleware stack. This will cache responses based on ETag fingerprints and serve them back for subsequent 304 responses.

    # Add gem 'faraday-http-cache' to your Gemfile
    
    stack = Faraday::RackBuilder.new do |builder|
      builder.use Faraday::HttpCache, serializer: Marshal, shared_cache: false
      builder.use Octokit::Response::RaiseError
      builder.adapter Faraday.default_adapter
    end
    Octokit.middleware = stack
  5. Install Octokit via Rubygems or Gemfile

    main

    You can install Octokit by running the gem install command or by adding it to your Gemfile.

    To install via Rubygems:

    gem install octokit

    To add to your Gemfile:

    gem "octokit"

    Then, access the library in your Ruby code using:

    require 'octokit'
    gem install octokit
  6. Set network timeouts

    main

    By default, Octokit does not timeout network requests. To prevent blocking your server, pass Faraday timeout settings into connection_options via the configuration block.

    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
  7. Use environment variables for configuration

    main

    Many Octokit attributes automatically look for default values in environment variables before falling back to internal defaults. For example, setting OCTOKIT_API_ENDPOINT will configure the api_endpoint.

    To disable deprecation warnings and development preview warnings from being printed to STDOUT, set the environment variable: OCTOKIT_SILENT=true

  8. Configure module-level defaults

    main

    Octokit allows setting configuration options at the module level using Octokit.configure. These defaults apply to all new client instances created after the configuration is set.

    Supported attributes include:

    • api_endpoint
    • web_endpoint
    • access_token
    • manage_ghes_endpoint
    • manage_ghes_username
    • manage_ghes_password
    # Set attributes one at a time
    Octokit.api_endpoint = 'http://api.github.dev'
    
    # Set attributes in a batch
    Octokit.configure do |c|
      c.api_endpoint = 'http://api.github.dev'
      c.web_endpoint = 'http://github.dev'
    end
  9. Enable Auto Pagination

    main

    When auto_paginate is enabled, Octokit will automatically fetch and concatenate results from all pages into a single array. Note that this sets the page size to 100 and may consume more of your rate limit.

    To enable it for a specific client instance:

    client.auto_paginate = true

    To enable it globally for all Octokit client instances:

    Octokit.configure do |c|
      c.auto_paginate = true
    end
    client.auto_paginate = true
    issues = client.issues 'rails/rails'
    issues.length
    # => 702
  10. Configure default results per page

    main

    The GitHub API defaults to 30 results per page. You can increase this during client initialization using the per_page option (up to 100).

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

    main

    Octokit raises Ruby exceptions when the API returns an error. All exceptions inherit from Octokit::Error and provide access to #response_status, #response_headers, and #response_body.

    Common error mappings:

    • 400 Bad Request $\rightarrow$ Octokit::BadRequest
    • 403 Forbidden (rate limited) $\rightarrow$ Octokit::TooManyRequests

    For validation errors, the #errors method returns an Array of Hashes containing detailed information from the API.

  12. Disable SSL verification for GitHub Enterprise

    main

    If you need to temporarily disable SSL verification during the initial setup of a GitHub Enterprise installation, you can modify the connection_options on your client instance.

    Warning: Ensure you set :verify back to true once setup is complete to maintain secure communication.

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