octokit.js

octokit.js

全功能GitHub平台API开发工具包

octokit.js是一个适用于浏览器、Node.js和Deno的GitHub开发工具包。它整合了API、App和Action客户端,全面覆盖GitHub平台API,包括REST API、GraphQL和身份验证等功能。这个SDK通用性强,易于扩展和定制,可满足多样化的GitHub开发需求。

OctokitGitHub SDKAPI客户端认证REST APIGithub开源项目

octokit.js

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.

The octokit package integrates the three main Octokit libraries

  1. API client (REST API requests, GraphQL API queries, Authentication)
  2. App client (GitHub App & installations, Webhooks, OAuth)
  3. Action client (Pre-authenticated API client for single repository)

Table of contents <!-- omit in toc -->

<!-- toc --> <!-- tocstop -->

Features

  • Complete. All features of GitHub's platform APIs are covered.
  • Prescriptive. All recommended best practices are implemented.
  • Universal. Works in all modern browsers, Node.js, and Deno.
  • Tested. All libraries have a 100% test coverage.
  • Typed. All libraries have extensive TypeScript declarations.
  • Decomposable. Use only the code you need. You can build your own Octokit in only a few lines of code or use the underlying static methods. Make your own tradeoff between functionality and bundle size.
  • Extendable. A feature missing? Add functionalities with plugins, hook into the request or webhook lifecycle or implement your own authentication strategy.

Usage

<table> <tbody valign=top align=left> <tr><th> Browsers </th><td width=100%> Load <code>octokit</code> directly from <a href="https://esm.sh">esm.sh</a>
<script type="module"> import { Octokit, App } from "https://esm.sh/octokit"; </script>
</td></tr> <tr><th> Deno </th><td width=100%> Load <code>octokit</code> directly from <a href="https://esm.sh">esm.sh</a>
import { Octokit, App } from "https://esm.sh/octokit?dts";
</td></tr> <tr><th> Node </th><td>

Install with <code>npm/pnpm install octokit</code>, or <code>yarn add octokit</code>

import { Octokit, App } from "octokit";
</td></tr> </tbody> </table>

[!IMPORTANT] As we use conditional exports, you will need to adapt your tsconfig.json by setting "moduleResolution": "node16", "module": "node16".

See the TypeScript docs on package.json "exports".<br> See this helpful guide on transitioning to ESM from @sindresorhus

Octokit API Client

standalone minimal Octokit: @octokit/core.

The Octokit client can be used to send requests to GitHub's REST API and queries to GitHub's GraphQL API.

Example: Get the username for the authenticated user.

// Create a personal access token at https://github.com/settings/tokens/new?scopes=repo const octokit = new Octokit({ auth: `personal-access-token123` }); // Compare: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user const { data: { login }, } = await octokit.rest.users.getAuthenticated(); console.log("Hello, %s", login);

Constructor options

The most commonly used options are

<table> <thead align=left> <tr> <th> name </th> <th> type </th> <th width=100%> description </th> </tr> </thead> <tbody align=left valign=top> <tr> <th> <code>userAgent</code> </th> <td> <code>String</code> </td> <td>

Setting a user agent is required for all requests sent to GitHub's Platform APIs. The user agent defaults to something like this: octokit.js/v1.2.3 Node.js/v8.9.4 (macOS High Sierra; x64). It is recommend to set your own user agent, which will prepend the default one.

const octokit = new Octokit({ userAgent: "my-app/v1.2.3", });
</td> </tr> <tr> <th> <code>authStrategy</code> </th> <td> <code>Function</code> </td> <td>

Defaults to @octokit/auth-token.

See Authentication below.

</td> </tr> <tr> <th> <code>auth</code> </th> <td> <code>String</code> or <code>Object</code> </td> <td>

Set to a personal access token unless you changed the authStrategy option.

See Authentication below.

</td> </tr> <tr> <th> <code>baseUrl</code> </th> <td> <code>String</code> </td> <td>

When using with GitHub Enterprise Server, set options.baseUrl to the root URL of the API. For example, if your GitHub Enterprise Server's hostname is github.acme-inc.com, then set options.baseUrl to https://github.acme-inc.com/api/v3. Example

const octokit = new Octokit({ baseUrl: "https://github.acme-inc.com/api/v3", });
</td> </tr> </tbody> </table>

Advanced options

<table> <thead align=left> <tr> <th> name </th> <th> type </th> <th width=100%> description </th> </tr> </thead> <tbody align=left valign=top> <tr> <th> <code>request</code> </th> <td> <code>Object</code> </td> <td>

Node only

  • request.timeout sets a request timeout, defaults to 0

The request option can also be set on a per-request basis.

</td></tr> <tr> <th> <code>timeZone</code> </th> <td> <code>String</code> </td> <td>

Sets the Time-Zone header which defines a timezone according to the list of names from the Olson database.

const octokit = new Octokit({ timeZone: "America/Los_Angeles", });

The time zone header will determine the timezone used for generating the timestamp when creating commits. See GitHub's Timezones documentation.

</td> </tr> <tr> <th> <code>throttle</code> </th> <td> <code>Object</code> </td> <td>

Octokit implements request throttling using @octokit/plugin-throttling

By default, requests are retried once and warnings are logged in case of hitting a rate or secondary rate limit.

{ onRateLimit: (retryAfter, options, octokit) => { octokit.log.warn( `Request quota exhausted for request ${options.method} ${options.url}` ); if (options.request.retryCount === 0) { // only retries once octokit.log.info(`Retrying after ${retryAfter} seconds!`); return true; } }, onSecondaryRateLimit: (retryAfter, options, octokit) => { octokit.log.warn( `SecondaryRateLimit detected for request ${options.method} ${options.url}` ); if (options.request.retryCount === 0) { // only retries once octokit.log.info(`Retrying after ${retryAfter} seconds!`); return true; } }, };

To opt-out of this feature:

new Octokit({ throttle: { enabled: false } });

Throttling in a cluster is supported using a Redis backend. See @octokit/plugin-throttling Clustering

</td> </tr> <tr> <th> <code>retry</code> </th> <td> <code>Object</code> </td> <td>

Octokit implements request retries using @octokit/plugin-retry

To opt-out of this feature:

new Octokit({ retry: { enabled: false } });
</td> </tr> </tbody> </table>

Authentication

By default, the Octokit API client supports authentication using a static token.

There are different means of authentication that are supported by GitHub, that are described in detail at octokit/authentication-strategies.js. You can set each of them as the authStrategy constructor option, and pass the strategy options as the auth constructor option.

For example, in order to authenticate as a GitHub App Installation:

import { createAppAuth } from "@octokit/auth-app"; const octokit = new Octokit({ authStrategy: createAppAuth, auth: { appId: 1, privateKey: "-----BEGIN PRIVATE KEY-----\n...", installationId: 123, }, }); // authenticates as app based on request URLs const { data: { slug }, } = await octokit.rest.apps.getAuthenticated(); // creates an installation access token as needed // assumes that installationId 123 belongs to @octocat, otherwise the request will fail await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello world from " + slug, });

You can use the App or OAuthApp SDKs which provide APIs and internal wiring to cover most use cases.

For example, to implement the above using App

const app = new App({ appId, privateKey }); const { data: slug } = await app.octokit.rest.apps.getAuthenticated(); const octokit = await app.getInstallationOctokit(123); await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello world from " + slug, });

Learn more about how authentication strategies work or how to create your own.

Proxy Servers (Node.js only)

By default, the Octokit API client does not make use of the standard proxy server environment variables. To add support for proxy servers you will need to provide an https client that supports them such as undici.ProxyAgent().

For example, this would use a ProxyAgent to make requests through a proxy server:

import { fetch as undiciFetch, ProxyAgent } from 'undici'; const myFetch = (url, options) => { return undiciFetch(url, { ...options, dispatcher: new ProxyAgent(<your_proxy_url>) }) } const octokit = new Octokit({ request: { fetch: myFetch }, });

If you are writing a module that uses Octokit and is designed to be used by other people, you should ensure that consumers can provide an alternative agent for your Octokit or as a parameter to specific calls such as:

import { fetch as undiciFetch, ProxyAgent } from 'undici'; const myFetch = (url, options) => { return undiciFetch(url, { ...options, dispatcher: new ProxyAgent(<your_proxy_url>) }) } octokit.rest.repos.get({ owner, repo, request: { fetch: myFetch }, });

Fetch missing

If you get the following error:

fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}).

It probably means you are trying to run Octokit with an unsupported version of NodeJS. Octokit requires Node 18 or higher, which includes a native fetch API.

To bypass this problem you can provide your own fetch implementation (or a built-in version like node-fetch) like this:

import fetch from "node-fetch"; const octokit = new Octokit({ request: { fetch: fetch, }, });

REST API

There are two ways of using the GitHub REST API, the octokit.rest.* endpoint methods and octokit.request. Both act the same way, the octokit.rest.* methods are just added for convenience, they use octokit.request internally.

For example

await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello, world!", body: "I created this issue using Octokit!", });

Is the same as

await octokit.request("POST /repos/{owner}/{repo}/issues", { owner: "octocat", repo: "hello-world", title: "Hello, world!", body: "I created this issue using Octokit!", });

In both cases a given request is authenticated, retried, and throttled transparently by the octokit instance which also manages the accept and user-agent headers as needed.

octokit.request can be used to send requests to other domains by passing a full URL and to send requests to endpoints that are not (yet) documented in GitHub's REST API documentation.

octokit.rest endpoint methods

Every GitHub REST API endpoint has an associated octokit.rest endpoint method for better code readability and developer convenience. See @octokit/plugin-rest-endpoint-methods for full details.

Example: Create an issue

await octokit.rest.issues.create({ owner: "octocat", repo: "hello-world", title: "Hello, world!", body: "I created this issue using Octokit!", });

The octokit.rest endpoint methods are generated automatically from GitHub's OpenAPI specification. We track operation ID and parameter name changes in order to implement deprecation warnings and reduce the frequency of breaking changes.

Under the covers, every endpoint method is just octokit.request with defaults set, so it supports the same parameters as well as the .endpoint() API.

octokit.request()

You can call the GitHub REST API directly using octokit.request. The request API matches GitHub's REST API documentation 1:1 so anything you see there, you can call using request. See @octokit/request for all the details.

Example: Create an issue

[![Screenshot of REST API reference documentation for Create an

编辑推荐精选

TRAE编程

TRAE编程

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

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 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多