Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

octokit/octokit.js

Repository files navigation

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

Theoctokit 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

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, andDeno.
  • 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

BrowsersLoadoctokit directly fromesm.sh
<scripttype="module">import{Octokit,App}from"https://esm.sh/octokit";</script>
DenoLoadoctokit directly fromesm.sh
import{Octokit,App}from"https://esm.sh/octokit?dts";
Node

Install withnpm/pnpm install octokit, oryarn add octokit

import{Octokit,App}from"octokit";

Important

As we useconditional exports, you will need to adapt yourtsconfig.json by setting"moduleResolution": "node16", "module": "node16".

See the TypeScript docs onpackage.json "exports".
See thishelpful guide on transitioning to ESM from@sindresorhus

Octokit API Client

standalone minimal Octokit:@octokit/core.

TheOctokit client can be used to send requests toGitHub's REST API and queries toGitHub's GraphQL API.

Example: Get the username for the authenticated user.

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

Constructor options

The most commonly used options are

name type description
userAgentString

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.

constoctokit=newOctokit({userAgent:"my-app/v1.2.3",});
authStrategyFunction

Defaults to@octokit/auth-token.

SeeAuthentication below.

authString orObject

Set to apersonal access token unless you changed theauthStrategy option.

SeeAuthentication below.

baseUrlString

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

constoctokit=newOctokit({baseUrl:"https://github.acme-inc.com/api/v3",});

Advanced options

name type description
requestObject

Node only

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

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

timeZoneString

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

constoctokit=newOctokit({timeZone:"America/Los_Angeles",});

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

throttleObject

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 onceoctokit.log.info(`Retrying after${retryAfter} seconds!`);returntrue;}},onSecondaryRateLimit:(retryAfter,options,octokit)=>{octokit.log.warn(`SecondaryRateLimit detected for request${options.method}${options.url}`);if(options.request.retryCount===0){// only retries onceoctokit.log.info(`Retrying after${retryAfter} seconds!`);returntrue;}},};

To opt-out of this feature:

newOctokit({throttle:{enabled:false}});

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

retryObject

Octokit implements request retries using@octokit/plugin-retry

To opt-out of this feature:

newOctokit({retry:{enabled:false}});

Authentication

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

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

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

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

You can use theApp orOAuthApp SDKs which provide APIs and internal wiring to cover most use cases.

For example, to implement the above usingApp

constapp=newApp({ appId, privateKey});const{data:slug}=awaitapp.octokit.rest.apps.getAuthenticated();constoctokit=awaitapp.getInstallationOctokit(123);awaitoctokit.rest.issues.create({owner:"octocat",repo:"hello-world",title:"Hello world from "+slug,});

Learn more abouthow authentication strategies work or how tocreate your own.

Proxy Servers (Node.js only)

By default, theOctokit 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 asundici.ProxyAgent().

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

import{fetchasundiciFetch,ProxyAgent}from'undici';constmyFetch=(url,options)=>{returnundiciFetch(url,{    ...options,dispatcher:newProxyAgent(<your_proxy_url>)})}constoctokit=newOctokit({request:{fetch:myFetch},});

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

import{fetchasundiciFetch,ProxyAgent}from'undici';constmyFetch=(url,options)=>{returnundiciFetch(url,{    ...options,dispatcher:newProxyAgent(<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 ownfetch implementation (or a built-in version likenode-fetch) like this:

importfetchfrom"node-fetch";constoctokit=newOctokit({request:{fetch:fetch,},});

REST API

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

For example

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

Is the same as

awaitoctokit.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 theoctokit instance which also manages theaccept anduser-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 inGitHub's REST API documentation.

octokit.rest endpoint methods

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

Example:Create an issue

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

Theoctokit.rest endpoint methods are generated automatically fromGitHub'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 justoctokit.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 usingoctokit.request. Therequest API matches GitHub's REST API documentation 1:1 so anything you see there, you can call usingrequest. See@octokit/request for all the details.

Example:Create an issue

Screenshot of REST API reference documentation for Create an issue

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

// https://docs.github.com/en/rest/reference/issues#create-an-issueawaitoctokit.request("POST /repos/{owner}/{repo}/issues",{owner:"octocat",repo:"hello-world",title:"Hello, world!",body:"I created this issue using Octokit!",});

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 theoctokit.rest.*.list* methods for convenience and better code readability.

Example: iterate through all issues in a repository

constiterator=octokit.paginate.iterator(octokit.rest.issues.listForRepo,{owner:"octocat",repo:"hello-world",per_page:100,});// iterate through each responseforawait(const{data:issues}ofiterator){for(constissueofissues){console.log("Issue #%d: %s",issue.number,issue.title);}}

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

constissues=awaitoctokit.paginate(octokit.rest.issues.listForRepo,{owner:"octocat",repo:"hello-world",per_page:100,});

Media Type formats

Media type formats can be set usingmediaType: { format } on every request.

Example: retrieve the raw content of apackage.json file

const{ data}=awaitoctokit.rest.repos.getContent({mediaType:{format:"raw",},owner:"octocat",repo:"hello-world",path:"package.json",});console.log("package name: %s",JSON.parse(data).name);

Learn more aboutMedia type formats.

Request error handling

Standalone module:@octokit/request-error

For request error handling, importRequestError and usetry...catch statement.

import{RequestError}from"octokit";
try{// your code here that sends at least one Octokit requestawaitoctokit.request("GET /");}catch(error){// Octokit errors are instances of RequestError, so they always have an `error.status` property containing the HTTP response code.if(errorinstanceofRequestError){// handle Octokit error// error.message; // Oops// error.status; // 500// error.request; // { method, url, headers, body }// error.response; // { url, status, headers, data }}else{// handle all other errorsthrowerror;}}

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 withoctokit.graphql.

Example: get the login of the authenticated user

const{viewer:{ login},}=awaitoctokit.graphql(`{  viewer {    login  }}`);

Variables can be passed as 2nd argument

const{ lastIssues}=awaitoctokit.graphql(`    query lastIssues($owner: String!, $repo: String!, $num: Int = 3) {      repository(owner: $owner, name: $repo) {        issues(last: $num) {          edges {            node {              title            }          }        }      }    }  `,{owner:"octokit",repo:"graphql.js",},);

Pagination

GitHub's GraphQL API returns a maximum of 100 items. If you want to retrieve all items, you can use the pagination API.

Example: get all issues

const{ allIssues}=awaitoctokit.graphql.paginate(`    query allIssues($owner: String!, $repo: String!, $num: Int = 10, $cursor: String) {      repository(owner: $owner, name: $repo) {        issues(first: $num, after: $cursor) {          edges {            node {              title            }          }          pageInfo {            hasNextPage            endCursor          }        }      }    }  `,{owner:"octokit",repo:"graphql.js",},);

Learn more aboutGitHub's GraphQL Pagination usage.

Schema previews

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

Example: create a label

awaitoctokit.graphql(`mutation createLabel($repositoryId:ID!,name:String!,color:String!) {  createLabel(input:{repositoryId:$repositoryId,name:$name}) {    label: {      id    }  }}`,{repositoryId:1,name:"important",color:"cc0000",mediaType:{previews:["bane"],},},);

Learn more aboutGitHub's GraphQL schema previews

App client

TheApp client combines features for GitHub Apps, Webhooks, and OAuth

GitHub App

Standalone module:@octokit/app

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.

TheApp client takes care of all that for you.

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

import{App}from"octokit";constapp=newApp({ appId, privateKey});forawait(const{ octokit, repository}ofapp.eachRepository.iterator()){// https://docs.github.com/en/rest/reference/repos#create-a-repository-dispatch-eventawaitoctokit.rest.repos.createDispatchEvent({owner:repository.owner.login,repo:repository.name,event_type:"my_event",client_payload:{foo:"bar",},});console.log("Event dispatched for %s",repository.full_name);}

Example: Get anoctokit instance authenticated as an installation

constoctokit=awaitapp.getInstallationOctokit(123);

Learn more aboutapps.

Webhooks

Standalone module:@octokit/webhooks

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.

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

Example: create a comment on new issues

import{createServer}from"node:http";import{App,createNodeMiddleware}from"octokit";constapp=newApp({  appId,  privateKey,webhooks:{ secret},});app.webhooks.on("issues.opened",({ octokit, payload})=>{returnoctokit.rest.issues.createComment({owner:payload.repository.owner.login,repo:payload.repository.name,issue_number:payload.issue.number,body:"Hello, World!",});});// Your app can now receive webhook events at `/api/github/webhooks`createServer(createNodeMiddleware(app)).listen(3000);

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

awaitapp.webhooks.verifyAndReceive({id:request.headers["x-github-delivery"],name:request.headers["x-github-event"],signature:request.headers["x-hub-signature-256"],payload:request.body,});

Learn more aboutGitHub webhooks.

OAuth

Standalone module:@octokit/oauth-app

Both OAuth Apps and GitHub Apps support authenticating GitHub users using OAuth, seeAuthorizing OAuth Apps andIdentifying 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, useOAuthApp instead.

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

import{createServer}from"node:http";import{App,createNodeMiddleware}from"octokit";constapp=newApp({oauth:{ clientId, clientSecret},});app.oauth.on("token.created",async({ token, octokit})=>{awaitoctokit.rest.activity.setRepoSubscription({owner:"octocat",repo:"hello-world",subscribed:true,});});// Your app can receive the OAuth redirect at /api/github/oauth/callback// Users can initiate the OAuth web flow by opening /api/github/oauth/logincreateServer(createNodeMiddleware(app)).listen(3000);

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

const{ token}=awaitapp.oauth.createToken({code:request.query.code,});

Example: create a token using the device flow.

const{ token}=awaitapp.oauth.createToken({asynconVerification(verification){awaitsendMessageToUser(request.body.phoneNumber,`Your code is${verification.user_code}. Enter it at${verification.verification_uri}`,);},});

Example: Create an OAuth App Server with default scopes

import{createServer}from"node:http";import{OAuthApp,createNodeMiddleware}from"octokit";constapp=newOAuthApp({  clientId,  clientSecret,defaultScopes:["repo","gist"],});app.oauth.on("token",async({ token, octokit})=>{awaitoctokit.rest.gists.create({description:"I created this gist using Octokit!",public:true,files:{"example.js":`/* some code here */`,},});});// Your app can receive the OAuth redirect at /api/github/oauth/callback// Users can initiate the OAuth web flow by opening /api/oauth/logincreateServer(createNodeMiddleware(app)).listen(3000);

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 usecreateNodeMiddleware(), it works with both, Node'shttp.createServer() method as well as anExpress middleware.

The default routes that the middleware exposes are

RouteRoute Description
POST /api/github/webhooksEndpoint to receive GitHub Webhook Event requests
GET /api/github/oauth/loginRedirects to GitHub's authorization endpoint. Accepts optional?state and?scopes query parameters.?scopes is a comma-separated list ofsupported OAuth scope names
GET /api/github/oauth/callbackThe client's redirect endpoint. This is where thetoken event gets triggered
POST /api/github/oauth/tokenExchange an authorization code for an OAuth Access token. If successful, thetoken event gets triggered.
GET /api/github/oauth/tokenCheck if token is valid. Must authenticate using token inAuthorization header. Uses GitHub'sPOST /applications/{client_id}/token endpoint
PATCH /api/github/oauth/tokenResets a token (invalidates current one, returns new token). Must authenticate using token inAuthorization header. Uses GitHub'sPATCH /applications/{client_id}/token endpoint.
PATCH /api/github/oauth/refresh-tokenRefreshes an expiring token (invalidates current one, returns new access token and refresh token). Must authenticate using token inAuthorization header. Uses GitHub'sPOST https://github.com/login/oauth/access_token OAuth endpoint.
POST /api/github/oauth/token/scopedCreates a scoped token (does not invalidate the current one). Must authenticate using token inAuthorization header. Uses GitHub'sPOST /applications/{client_id}/token/scoped endpoint.
DELETE /api/github/oauth/tokenInvalidates current token, basically the equivalent of a logout. Must authenticate using token inAuthorization header.
DELETE /api/github/oauth/grantRevokes the user's grant, basically the equivalent of an uninstall. must authenticate using token inAuthorization header.

Example: create a GitHub server with express

importexpressfrom"express";import{App,createNodeMiddleware}from"octokit";constexpressApp=express();constoctokitApp=newApp({  appId,  privateKey,webhooks:{ secret},oauth:{ clientId, clientSecret},});expressApp.use(createNodeMiddleware(app));expressApp.listen(3000,()=>{console.log(`Example app listening at http://localhost:3000`);});

OAuth for browser apps

You must not expose your app's client secret to the user, so you cannot use theApp constructor. Instead, you have to create a server using theApp 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 thestate parameter to the value returned byapp.oauthLoginUrl() earlier to protect against forgery attacks, then exchange thecode for an OAuth Authorization token.

If you run anapp 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

constcode=newURL(location.href).searchParams.get("code");if(code){// remove ?code=... from URLconstpath=location.pathname+location.search.replace(/\b(code|state)=\w+/g,"").replace(/[?&]+$/,"");history.replaceState({},"",path);// exchange the code for a token with your backend.// If you use https://github.com/octokit/oauth-app.js// the exchange would look something like thisconstresponse=awaitfetch("/api/github/oauth/token",{method:"POST",headers:{"content-type":"application/json",},body:JSON.stringify({ code}),});const{ token}=awaitresponse.json();// `token` is the OAuth Access Token that can be useconst{ Octokit}=awaitimport("https://esm.sh/@octokit/core");constoctokit=newOctokit({auth:token});const{data:{ login},}=awaitoctokit.request("GET /user");alert("Hi there, "+login);}

🚧 We are working on@octokit/auth-oauth-user-client to provide a simple API for all methods related to OAuth user tokens.

The plan is to add an newGET /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-authenticatedoctokit Instance available.

Action client

standalone module:@octokit/action

🚧 A fully fledgedAction client is pending. You can use@actions/github for the time being

LICENSE

MIT

About

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

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp