Extendable client for GitHub's REST & GraphQL APIs
- Usage
- Options
- Defaults
- Authentication
- Logging
- Hooks
- Plugins
- Build your own Octokit with Plugins and Defaults
- LICENSE
If you need a minimalistic library to utilize GitHub's REST API and GraphQL API which you can extend with plugins as needed, then @octokit/core is a great starting point.
If you don't need the Plugin API then using @octokit/request or @octokit/graphql directly is a good alternative.
| Browsers |
Load @octokit/core directly from cdn.skypack.dev<scripttype="module">import{Octokit}from"https://cdn.skypack.dev/@octokit/core";</script> |
|---|---|
| Node | Install with const{ Octokit }=require("@octokit/core");// or: import { Octokit } from "@octokit/core"; |
// Create a personal access token at https://github.com/settings/tokens/new?scopes=repoconstoctokit=newOctokit({auth: `personal-access-token123`});constresponse=awaitoctokit.request("GET /orgs/:org/repos",{org: "octokit",type: "private",});See @octokit/request for full documentation of the .request method.
constoctokit=newOctokit({auth: `secret123`});constresponse=awaitoctokit.graphql(`query ($login: String!) { organization(login: $login) { repositories(privacy: PRIVATE) { totalCount } } }`,{login: "octokit"});See @octokit/graphql for full documentation of the .graphql method.
| name | type | description |
|---|---|---|
options.authStrategy | Function |
Defaults to @octokit/auth-token. See Authentication below for examples.
|
options.auth | String or Object | See Authentication below for examples. |
options.baseUrl | String | When using with GitHub Enterprise Server, set constoctokit=newOctokit({baseUrl: "https://github.acme-inc.com/api/v3",}); |
options.previews | Array of Strings | Some REST API endpoints require preview headers to be set, or enable additional features. Preview headers can be set on a per-request basis, e.g. octokit.request("POST /repos/:owner/:repo/pulls",{mediaType: {previews: ["shadow-cat"],},
owner,
repo,title: "My pull request",base: "master",head: "my-feature",draft: true,});You can also set previews globally, by setting the constoctokit=newOctokit({previews: ["shadow-cat"],}); |
options.request | Object | Set a default request timeout ( There are more |
options.timeZone | String | Sets the constoctokit=newOctokit({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. |
options.userAgent | String | A custom user agent string for your app or library. Example constoctokit=newOctokit({userAgent: "my-app/v1.2.3",}); |
You can create a new Octokit class with customized default options.
constMyOctokit=Octokit.defaults({auth: "personal-access-token123",baseUrl: "https://github.acme-inc.com/api/v3",userAgent: "my-app/v1.2.3",});constoctokit1=newMyOctokit();constoctokit2=newMyOctokit();If you pass additional options to your new constructor, the options will be merged shallowly.
constMyOctokit=Octokit.defaults({foo: {opt1: 1,},});constoctokit=newMyOctokit({foo: {opt2: 1,},});// options will be { foo: { opt2: 1 }}If you need a deep or conditional merge, you can pass a function instead.
constMyOctokit=Octokit.defaults((options)=>{return{foo: Object.assign({},options.foo,{opt2: 1}),};});constoctokit=newMyOctokit({foo: {opt2: 1},});// options will be { foo: { opt1: 1, opt2: 1 }}Be careful about mutating the options object in the Octokit.defaults callback, as it can have unforeseen consequences.
Authentication is optional for some REST API endpoints accessing public data, but is required for GraphQL queries. Using authentication also increases your API rate limit.
By default, Octokit authenticates using the token authentication strategy. Pass in a token using options.auth. It can be a personal access token, an OAuth token, an installation access token or a JSON Web Token for GitHub App authentication. The Authorization header will be set according to the type of token.
import{Octokit}from"@octokit/core";constoctokit=newOctokit({auth: "mypersonalaccesstoken123",});const{ data }=awaitoctokit.request("/user");To use a different authentication strategy, set options.authStrategy. A set of officially supported authentication strategies can be retrieved from @octokit/auth. Example
import{Octokit}from"@octokit/core";import{createAppAuth}from"@octokit/auth-app";constappOctokit=newOctokit({authStrategy: createAppAuth,auth: {appId: 123,privateKey: process.env.PRIVATE_KEY,},});const{ data }=awaitappOctokit.request("/app");The .auth() method returned by the current authentication strategy can be accessed at octokit.auth(). Example
const{ token }=awaitappOctokit.auth({type: "installation",installationId: 123,});There are four built-in log methods
octokit.log.debug(message[, additionalInfo])octokit.log.info(message[, additionalInfo])octokit.log.warn(message[, additionalInfo])octokit.log.error(message[, additionalInfo])
They can be configured using the log client option. By default, octokit.log.debug() and octokit.log.info() are no-ops, while the other two call console.warn() and console.error() respectively.
This is useful if you build reusable plugins.
If you would like to make the log level configurable using an environment variable or external option, we recommend the console-log-level package. Example
constoctokit=newOctokit({log: require("console-log-level")({level: "info"}),});You can customize Octokit's request lifecycle with hooks.
octokit.hook.before("request",async(options)=>{validate(options);});octokit.hook.after("request",async(response,options)=>{console.log(`${options.method}${options.url}: ${response.status}`);});octokit.hook.error("request",async(error,options)=>{if(error.status===304){returnfindInCache(error.headers.etag);}throwerror;});octokit.hook.wrap("request",async(request,options)=>{// add logic before, after, catch errors or replace the request altogetherreturnrequest(options);});See before-after-hook for more documentation on hooks.
Octokit’s functionality can be extended using plugins. The Octokit.plugin() method accepts a plugin (or many) and returns a new constructor.
A plugin is a function which gets two arguments:
- the current instance
- the options passed to the constructor.
In order to extend octokit's API, the plugin must return an object with the new methods.
// index.jsconst{ Octokit }=require("@octokit/core")constMyOctokit=Octokit.plugin(require("./lib/my-plugin"),require("octokit-plugin-example"));constoctokit=newMyOctokit({greeting: "Moin moin"});octokit.helloWorld();// logs "Moin moin, world!"octokit.request("GET /");// logs "GET / - 200 in 123ms"// lib/my-plugin.jsmodule.exports=(octokit,options={greeting: "Hello"})=>{// hook into the request lifecycleoctokit.hook.wrap("request",async(request,options)=>{consttime=Date.now();constresponse=awaitrequest(options);console.log(`${options.method}${options.url} – ${response.status} in ${Date.now()-time}ms`);returnresponse;});// add a custom methodreturn{helloWorld: ()=>console.log(`${options.greeting}, world!`);}};You can build your own Octokit class with preset default options and plugins. In fact, this is mostly how the @octokit/<context> modules work, such as @octokit/action:
const{ Octokit }=require("@octokit/core");constMyActionOctokit=Octokit.plugin(require("@octokit/plugin-paginate-rest"),require("@octokit/plugin-throttling"),require("@octokit/plugin-retry")).defaults({authStrategy: require("@octokit/auth-action"),userAgent: `my-octokit-action/v1.2.3`,});constoctokit=newMyActionOctokit();constinstallations=awaitoctokit.paginate("GET /app/installations");