Octokit

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

README

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


- [Octokit API Client](#octokit-api-client)
  - REST API
    - [octokit.rest endpoint methods](#octokitrest-endpoint-methods)
    - [octokit.request()](#octokitrequest)
    - Pagination
    - Schema previews
  - Webhooks
  - OAuth

Features


- Complete. All features of GitHub's platform APIs are covered.
- Prescriptive. All recommended best practises 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


Browsers
Load octokit directly from cdn.skypack.dev
        
  1. ``` html
  2. <script type="module">
  3. import { Octokit, App } from "https://cdn.skypack.dev/octokit";
  4. </script>
  5. ```

Deno
Load octokit directly from cdn.skypack.dev
        
  1. ```ts
  2. import { Octokit, App } from "https://cdn.skypack.dev/octokit?dts";
  3. ```

Node 12+

Install with npm install octokit, or yarn add octokit

  1. ``` js
  2. import { Octokit, App } from "octokit";
  3. ```

Node 10 and below

Install with npm install octokit, or yarn add octokit

  1. ``` js
  2. const { Octokit, App } = require("octokit");
  3. ```


Octokit API Client


standalone minimal Octokit: [@octokit/core](https://github.com/octokit/core.js/#readme).

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.

  1. ``` js
  2. // Create a personal access token at https://github.com/settings/tokens/new?scopes=repo
  3. const octokit = new Octokit({ auth: `personal-access-token123` });

  4. // Compare: https://docs.github.com/en/rest/reference/users#get-the-authenticated-user
  5. const {
  6.   data: { login },
  7. } = await octokit.rest.users.getAuthenticated();
  8. console.log("Hello, %s", login);
  9. ```

Constructor options


The most commonly used options are

        name
        type
        description
userAgent String

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.

  1. ``` js
  2. const octokit = new Octokit({
  3.   userAgent: "my-app/v1.2.3",
  4. });
  5. ```

authStrategy Function

Defaults to [@octokit/auth-token](https://github.com/octokit/auth-token.js#readme).

See Authentication below.

auth String or Object

Set to a personal access token unless you changed theauthStrategy option.

See Authentication below.

baseUrl String

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

  1. ``` js
  2. const octokit = new Octokit({
  3.   baseUrl: "https://github.acme-inc.com/api/v3",
  4. });
  5. ```


Advanced options

        name
        type
        description
request Object

- request.signal: Use an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) instance to cancel a request. [abort-controller](https://www.npmjs.com/package/abort-controller) is an implementation for Node.
- request.fetch: Replacement for built-in fetch method. Useful for testing with [fetch-mock](https://github.com/wheresrhys/fetch-mock)

Node only

- request.timeout sets a request timeout, defaults to 0
- request.agent: A [http(s).Agent](https://nodejs.org/api/http.html#http_class_http_agent) e.g. for proxy usage

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

timeZone String

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

  1. ``` js
  2. const octokit = new Octokit({
  3.   timeZone: "America/Los_Angeles",
  4. });
  5. ```

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

throttle Object

Octokit implements request throttling using [@octokit/plugin-throttling](https://github.com/octokit/plugin-throttling.js/#readme)

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

  1. ``` js
  2. {
  3.   onRateLimit: (retryAfter, options, octokit) => {
  4.     octokit.log.warn(
  5.       `Request quota exhausted for request ${options.method} ${options.url}`
  6.     );

  7.     if (options.request.retryCount === 0) {
  8.       // only retries once
  9.       octokit.log.info(`Retrying after ${retryAfter} seconds!`);
  10.       return true;
  11.     }
  12.   },
  13.   onSecondaryRateLimit: (retryAfter, options, octokit) => {
  14.     octokit.log.warn(
  15.       `SecondaryRateLimit detected for request ${options.method} ${options.url}`
  16.     );

  17.     if (options.request.retryCount === 0) {
  18.       // only retries once
  19.       octokit.log.info(`Retrying after ${retryAfter} seconds!`);
  20.       return true;
  21.     }
  22.   },
  23. };
  24. ```

To opt-out of this feature:

  1. ``` js
  2. new Octokit({ throttle: { enabled: false } });
  3. ```

Throttling in a cluster is supported using a Redis backend. See [@octokit/plugin-throttling Clustering](https://github.com/octokit/plugin-throttling.js/#clustering)

retry Object

Octokit implements request retries using [@octokit/plugin-retry](https://github.com/octokit/plugin-retry.js/#readme)

To opt-out of this feature:

  1. ``` js
  2. new Octokit({ retry: { enabled: false } });
  3. ```


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 theauthStrategy constructor option, and pass the strategy options as the auth constructor option.

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

  1. ``` js
  2. import { createAppAuth } from "@octokit/auth-app";
  3. const octokit = new Octokit({
  4.   authStrategy: createAppAuth,
  5.   auth: {
  6.     appId: 1,
  7.     privateKey: "-----BEGIN PRIVATE KEY-----\n...",
  8.     installationId: 123,
  9.   },
  10. });

  11. // authenticates as app based on request URLs
  12. const {
  13.   data: { slug },
  14. } = await octokit.rest.apps.getAuthenticated();

  15. // creates an installation access token as needed
  16. // assumes that installationId 123 belongs to @octocat, otherwise the request will fail
  17. await octokit.rest.issues.create({
  18.   owner: "octocat",
  19.   repo: "hello-world",
  20.   title: "Hello world from " + slug,
  21. });
  22. ```

In most cases you can use the [App](#github-app) or [OAuthApp](#oauth-app) SDK which provide APIs and internal wiring to cover most usecase.

For example, to implement the above using App

  1. ``` js
  2. const app = new App({ appId, privateKey });
  3. const { data: slug } = await app.octokit.rest.apps.getAuthenticated();
  4. const octokit = await app.getInstallationOctokit(123);
  5. await octokit.rest.issues.create({
  6.   owner: "octocat",
  7.   repo: "hello-world",
  8.   title: "Hello world from " + slug,
  9. });
  10. ```


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 proxy-agent.

For example, this would use a proxy-agent generated client that would configure the proxy based on the standard environment variables http_proxy, https_proxy and no_proxy:

  1. ``` js
  2. import ProxyAgent from "proxy-agent";

  3. const octokit = new Octokit({
  4.   request: {
  5.     agent: new ProxyAgent(),
  6.   },
  7. });
  8. ```

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:

  1. ``` js
  2. octokit.rest.repos.get({
  3.   owner,
  4.   repo,
  5.   request: { agent },
  6. });
  7. ```

REST API


There are two ways of using the GitHub REST API, the [`octokit.rest. endpoint methods](#octokitrest-endpoint-methods) and [octokit.request](#octokitrequest). Both act the same way, the octokit.rest. methods are just added for convenience, they use octokit.request` internally.

For example

  1. ``` js
  2. await octokit.rest.issues.create({
  3.   owner: "octocat",
  4.   repo: "hello-world",
  5.   title: "Hello, world!",
  6.   body: "I created this issue using Octokit!",
  7. });
  8. ```

Is the same as

  1. ``` js
  2. await octokit.request("POST /repos/{owner}/{repo}/issues", {
  3.   owner: "octocat",
  4.   repo: "hello-world",
  5.   title: "Hello, world!",
  6.   body: "I created this issue using Octokit!",
  7. });
  8. ```

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](https://github.com/octokit/plugin-rest-endpoint-methods.js/#readme) for full details.


  1. ``` js
  2. await octokit.rest.issues.create({
  3.   owner: "octocat",
  4.   repo: "hello-world",
  5.   title: "Hello, world!",
  6.   body: "I created this issue using Octokit!",
  7. });
  8. ```

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](https://github.com/octokit/request.js#readme) for all the details.

Screenshot of REST API reference documentation for Create an issue

The octokit.request API call corresponding to that issue creation documentation looks like this:

  1. ``` js
  2. // https://docs.github.com/en/rest/reference/issues#create-an-issue
  3. await octokit.request("POST /repos/{owner}/{repo}/issues", {
  4.   owner: "octocat",
  5.   repo: "hello-world",
  6.   title: "Hello, world!",
  7.   body: "I created this issue using Octokit!",
  8. });
  9. ```

The 1st argument is the REST API route as listed in GitHub's API documentation. The 2nd argument is an object with all parameters, independent of whether they are used in the path, query, or body.

Pagination


All REST API endpoints that paginate return the first 30 items by default. If you want to retrieve all items, you can use the pagination API. The pagination API expects the REST API route as first argument, but you can also pass any of the `octokit.rest..list` methods for convenience and better code readability.

Example: iterate through all issues in a repository

  1. ``` js
  2. const iterator = octokit.paginate.iterator(octokit.rest.issues.listForRepo, {
  3.   owner: "octocat",
  4.   repo: "hello-world",
  5.   per_page: 100,
  6. });

  7. // iterate through each response
  8. for await (const { data: issues } of iterator) {
  9.   for (const issue of issues) {
  10.     console.log("Issue #%d: %s", issue.number, issue.title);
  11.   }
  12. }
  13. ```

Using the async iterator is the most memory efficient way to iterate through all items. But you can also retrieve all items in a single call

  1. ``` js
  2. const issues = await octokit.paginate(octokit.rest.issues.listForRepo, {
  3.   owner: "octocat",
  4.   repo: "hello-world",
  5.   per_page: 100,
  6. });
  7. ```

Media Type previews and formats


Note: The concept of _preview headers_ has been deprecated from REST API endpoints hosted via api.github.com but it still exists in GHES (GitHub Enterprise Server) version 3.2 and below. Instead of using _preview headers_ going forward, new features are now being tested using beta previews that users will have to opt-in to.

Media type previews and formats can be set using mediaType: { format, previews } on every request. Required API previews are set automatically on the respective REST API endpoint methods.

Example: retrieve the raw content of a package.json file

  1. ``` js
  2. const { data } = await octokit.rest.repos.getContent({
  3.   mediaType: {
  4.     format: "raw",
  5.   },
  6.   owner: "octocat",
  7.   repo: "hello-world",
  8.   path: "package.json",
  9. });
  10. console.log("package name: %s", JSON.parse(data).name);
  11. ```

Example: retrieve a repository with topics

  1. ``` js
  2. const { data } = await octokit.rest.repos.getContent({
  3.   mediaType: {
  4.     previews: ["mercy"],
  5.   },
  6.   owner: "octocat",
  7.   repo: "hello-world",
  8. });
  9. console.log("topics on octocat/hello-world: %j", data.topics);
  10. ```

Learn more about Media type formats and previews used on GitHub Enterprise Server.

GraphQL API queries


Octokit also supports GitHub's GraphQL API directly -- you can use the same queries shown in the documentation and available in the GraphQL explorer in your calls with octokit.graphql.

Example: get the login of the authenticated user

  1. ``` js
  2. const {
  3.   viewer: { login },
  4. } = await octokit.graphql(`{
  5.   viewer {
  6.     login
  7.   }
  8. }`);
  9. ```

Variables can be passed as 2nd argument

  1. ``` js
  2. const { lastIssues } = await octokit.graphql(
  3.   `
  4.     query lastIssues($owner: String!, $repo: String!, $num: Int = 3) {
  5.       repository(owner: $owner, name: $repo) {
  6.         issues(last: $num) {
  7.           edges {
  8.             node {
  9.               title
  10.             }
  11.           }
  12.         }
  13.       }
  14.     }
  15.   `,
  16.   {
  17.     owner: "octokit",
  18.     repo: "graphql.js",
  19.   }
  20. );
  21. ```

Schema previews


Previews can be enabled using the {mediaType: previews: [] } option.

Example: create a label

  1. ``` js
  2. await octokit.graphql(
  3.   `mutation createLabel($repositoryId:ID!,name:String!,color:String!) {
  4.   createLabel(input:{repositoryId:$repositoryId,name:$name}) {
  5.     label: {
  6.       id
  7.     }
  8.   }
  9. }`,
  10.   {
  11.     repositoryId: 1,
  12.     name: "important",
  13.     color: "cc0000",
  14.     mediaType: {
  15.       previews: ["bane"],
  16.     },
  17.   }
  18. );
  19. ```


App client


The App client combines features for GitHub Apps, Webhooks, and OAuth

GitHub App


Standalone module: [@octokit/app](https://github.com/octokit/app.js/#readme)

For integrators, GitHub Apps are a means of authentication and authorization. A GitHub app can be registered on a GitHub user or organization account. A GitHub App registration defines a set of permissions and webhooks events it wants to receive and provides a set of credentials in return. Users can grant access to repositories by installing them.

Some API endpoints require the GitHub app to authenticate as itself using a JSON Web Token (JWT). For requests affecting an installation, an installation access token has to be created using the app's credentials and the installation ID.

The App client takes care of all that for you.

Example: Dispatch a repository event in every repository the app is installed on

  1. ``` js
  2. import { App } from "octokit";

  3. const app = new App({ appId, privateKey });

  4. for await (const { octokit, repository } of app.eachRepository.iterator()) {
  5.   // https://docs.github.com/en/rest/reference/repos#create-a-repository-dispatch-event
  6.   await octokit.rest.repos.createDispatchEvent({
  7.     owner: repository.owner.login,
  8.     repo: repository.name,
  9.     event_type: "my_event",
  10.     client_payload: {
  11.       foo: "bar",
  12.     },
  13.   });
  14.   console.log("Event distpatched for %s", repository.full_name);
  15. }
  16. ```

Example: Get an octokit instance authenticated as an installation

  1. ``` js
  2. const octokit = await app.getInstallationOctokit(123);
  3. ```

Learn more about apps.

Webhooks


Standalone module: [@octokit/webhooks](https://github.com/octokit/webhooks.js/#readme)

When installing an app, events that the app registration requests will be sent as requests to the webhook URL set in the app's registration.

Webhook event requests are signed using the webhook secret, which is also part of the app's registration. You must verify that secret before handling the request payload.

The app.webhooks.* APIs provide methods to receiving, verifying, and handling webhook events.

Example: create a comment on new issues

  1. ``` js
  2. import { App, createNodeMiddleware } from "octokit";

  3. const app = new App({
  4.   appId,
  5.   privateKey,
  6.   webhooks: { secret },
  7. });

  8. app.webhooks.on("issues.opened", ({ octokit, payload }) => {
  9.   return octokit.rest.issues.createComment({
  10.     owner: payload.repository.owner.login,
  11.     repo: payload.repository.name,
  12.     body: "Hello, World!",
  13.   });
  14. });

  15. // Your app can now receive webhook events at `/api/github/webhooks`
  16. require("http").createServer(createNodeMiddleware(app)).listen(3000);
  17. ```

For serverless environments, you can explicitly verify and receive an event

  1. ``` js
  2. await app.webhooks.verifyAndReceive({
  3.   id: request.headers["x-github-delivery"],
  4.   name: request.headers["x-github-event"],
  5.   signature: request.headers["x-hub-signature-256"],
  6.   payload: request.body,
  7. });
  8. ```

Learn more about GitHub webhooks.

OAuth


Standalone module: [@octokit/oauth-app](https://github.com/octokit/oauth-app.js/#readme)

Both OAuth Apps and GitHub Apps support authenticating GitHub users using OAuth, see Authorizing OAuth Apps and Identifying and authorizing users for GitHub Apps.

There are some differences:

- Only OAuth Apps support scopes. GitHub apps have permissions, and access is granted via installations of the app on repositories.
- Only GitHub Apps support expiring user tokens
- Only GitHub Apps support creating a scoped token to reduce the permissions and repository access

App is for GitHub Apps. If you need OAuth App-specific functionality, use [OAuthApp instead](https://github.com/octokit/oauth-app.js/).

Example: Watch a repository when a user logs in using the OAuth web flow

  1. ``` js
  2. import { App, createNodeMiddleware } from "octokit";

  3. const app = new App({
  4.   oauth: { clientId, clientSecret },
  5. });

  6. app.oauth.on("token.created", async ({ token, octokit }) => {
  7.   await octokit.rest.activity.setRepoSubscription({
  8.     owner: "octocat",
  9.     repo: "hello-world",
  10.     subscribed: true,
  11.   });
  12. });

  13. // Your app can receive the OAuth redirect at /api/github/oauth/callback
  14. // Users can initiate the OAuth web flow by opening /api/oauth/login
  15. require("http").createServer(createNodeMiddleware(app)).listen(3000);
  16. ```

For serverless environments, you can explicitly exchange the code from the OAuth web flow redirect for an access token.
app.oauth.createToken() returns an authentication object and emits the "token.created" event.

  1. ``` js
  2. const { token } = await app.oauth.createToken({
  3.   code: request.query.code,
  4. });
  5. ```

Example: create a token using the device flow.

  1. ``` js
  2. const { token } = await app.oauth.createToken({
  3.   async onVerification(verification) {
  4.     await sendMessageToUser(
  5.       request.body.phoneNumber,
  6.       `Your code is ${verification.user_code}. Enter it at ${verification.verification_uri}`
  7.     );
  8.   },
  9. });
  10. ```

Example: Create an OAuth App Server with default scopes

  1. ``` js
  2. import { OAuthApp, createNodeMiddleware } from "octokit";

  3. const app = new OAuthApp({
  4.   clientId,
  5.   clientSecret,
  6.   defaultScopes: ["repo", "gist"],
  7. });

  8. app.oauth.on("token", async ({ token, octokit }) => {
  9.   await octokit.rest.gists.create({
  10.     description: "I created this gist using Octokit!",
  11.     public: true,
  12.     files: {
  13.       "example.js": `/* some code here */`,
  14.     },
  15.   });
  16. });

  17. // Your app can receive the OAuth redirect at /api/github/oauth/callback
  18. // Users can initiate the OAuth web flow by opening /api/oauth/login
  19. require("http").createServer(createNodeMiddleware(app)).listen(3000);
  20. ```

App Server


After registering your GitHub app, you need to create and deploy a server which can retrieve the webhook event requests from GitHub as well as accept redirects from the OAuth user web flow.

The simplest way to create such a server is to use createNodeMiddleware(), it works with both, Node's [http.createServer()](https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener) method as well as an Express middleware.

The default routes that the middleware exposes are

RouteRoute
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`POSTEndpoint
`GETRedirects
`GETThe
`POSTExchange
`GETCheck
`PATCHResets
`PATCHRefreshes
`POSTCreates
`DELETEInvalidates
`DELETERevokes

Example: create a GitHub server with express

  1. ``` js
  2. import express from "express";
  3. import { App, createNodeMiddleware } from "octokit";

  4. const expressApp = express();
  5. const octokitApp = new App({
  6.   appId,
  7.   privateKey,
  8.   webhooks: { secret },
  9.   oauth: { clientId, clientSecret },
  10. });

  11. expressApp.use(createNodeMiddleware(app));

  12. expressApp.listen(3000, () => {
  13.   console.log(`Example app listening at http://localhost:3000`);
  14. });
  15. ```

OAuth for browser apps


You must not expose your app's client secret to the user, so you cannot use the App constructor. Instead, you have to create a server using the App constructor which exposes the /api/github/oauth/* routes, through which you can safely implement an OAuth login for apps running in a web browser.

If you set (User) Authorization callback URL to your own app, than you need to read out the ?code=...&state=... query parameters, compare the state parameter to the value returned by app.oauthLoginUrl() earlier to protect against forgery attacks, then exchange the code for an OAuth Authorization token.

If you run an app server as described above, the default route to do that isPOST /api/github/oauth/token.

Once you successfully retrieved the token, it is also recommended to remove the ?code=...&state=... query parameters from the browser's URL

  1. ``` js
  2. const code = new URL(location.href).searchParams.get("code");
  3. if (code) {
  4.   // remove ?code=... from URL
  5.   const path =
  6.     location.pathname +
  7.     location.search.replace(/\b(code|state)=\w+/g, "").replace(/[?&]+$/, "");
  8.   history.pushState({}, "", path);

  9.   // exchange the code for a token with your backend.
  10.   // If you use https://github.com/octokit/oauth-app.js
  11.   // the exchange would look something like this
  12.   const response = await fetch("/api/github/oauth/token", {
  13.     method: "POST",
  14.     headers: {
  15.       "content-type": "application/json",
  16.     },
  17.     body: JSON.stringify({ code }),
  18.   });
  19.   const { token } = await response.json();
  20.   // `token` is the OAuth Access Token that can be use

  21.   const { Octokit } = await import("https://cdn.skypack.dev/@octokit/core");
  22.   const octokit = new Octokit({ auth: token });

  23.   const {
  24.     data: { login },
  25.   } = octokit.request("GET /user");
  26.   alert("Hi there, " + login);
  27. }
  28. ```

🚧 We are working on [@octokit/auth-oauth-user-client](https://github.com/octokit/auth-oauth-user-client.js#readme) to provide a simple API for all methods related to OAuth user tokens.

The plan is to add an new GET /api/github/oauth/octokit.js route to the node middleware which will return a JavaScript file that can be imported into an HTML file. It will make a pre-authenticated octokit Instance available.

Action client


standalone module: [@octokit/action](https://github.com/octokit/action.js#readme)

🚧 A fully fledged Action client is pending. You can use [@actions/github](https://github.com/actions/toolkit/tree/main/packages/github) for the time being

LICENSE