• Stars
    star
    1,145
  • Rank 39,152 (Top 0.8 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 23 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extendable client for GitHub's REST & GraphQL APIs

core.js

Extendable client for GitHub's REST & GraphQL APIs

@latest Build Status

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.

Usage

Browsers Load @octokit/core directly from cdn.skypack.dev
<script type="module">
  import { Octokit } from "https://cdn.skypack.dev/@octokit/core";
</script>
Node

Install with npm install @octokit/core

const { Octokit } = require("@octokit/core");
// or: import { Octokit } from "@octokit/core";

REST API example

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

const response = await octokit.request("GET /orgs/{org}/repos", {
  org: "octokit",
  type: "private",
});

See @octokit/request for full documentation of the .request method.

GraphQL example

const octokit = new Octokit({ auth: `secret123` });

const response = await octokit.graphql(
  `query ($login: String!) {
    organization(login: $login) {
      repositories(privacy: PRIVATE) {
        totalCount
      }
    }
  }`,
  { login: "octokit" }
);

See @octokit/graphql for full documentation of the .graphql method.

Options

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 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",
});
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: "main",
  head: "my-feature",
  draft: true,
});

You can also set previews globally, by setting the options.previews option on the constructor. Example:

const octokit = new Octokit({
  previews: ["shadow-cat"],
});
options.request Object

Set a default request timeout (options.request.timeout) or an http(s).Agent e.g. for proxy usage (Node only, options.request.agent).

There are more options.request.* options, see @octokit/request options. options.request can also be set on a per-request basis.

options.timeZone String

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.

options.userAgent String

A custom user agent string for your app or library. Example

const octokit = new Octokit({
  userAgent: "my-app/v1.2.3",
});

Defaults

You can create a new Octokit class with customized default options.

const MyOctokit = Octokit.defaults({
  auth: "personal-access-token123",
  baseUrl: "https://github.acme-inc.com/api/v3",
  userAgent: "my-app/v1.2.3",
});
const octokit1 = new MyOctokit();
const octokit2 = new MyOctokit();

If you pass additional options to your new constructor, the options will be merged shallowly.

const MyOctokit = Octokit.defaults({
  foo: {
    opt1: 1,
  },
});
const octokit = new MyOctokit({
  foo: {
    opt2: 1,
  },
});
// options will be { foo: { opt2: 1 }}

If you need a deep or conditional merge, you can pass a function instead.

const MyOctokit = Octokit.defaults((options) => {
  return {
    foo: Object.assign({}, options.foo, { opt1: 1 }),
  };
});
const octokit = new MyOctokit({
  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

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";

const octokit = new Octokit({
  auth: "mypersonalaccesstoken123",
});

const { data } = await octokit.request("/user");

To use a different authentication strategy, set options.authStrategy. A list of authentication strategies is available at octokit/authentication-strategies.js.

Example

import { Octokit } from "@octokit/core";
import { createAppAuth } from "@octokit/auth-app";

const appOctokit = new Octokit({
  authStrategy: createAppAuth,
  auth: {
    appId: 123,
    privateKey: process.env.PRIVATE_KEY,
  },
});

const { data } = await appOctokit.request("/app");

The .auth() method returned by the current authentication strategy can be accessed at octokit.auth(). Example

const { token } = await appOctokit.auth({
  type: "installation",
  installationId: 123,
});

Logging

There are four built-in log methods

  1. octokit.log.debug(message[, additionalInfo])
  2. octokit.log.info(message[, additionalInfo])
  3. octokit.log.warn(message[, additionalInfo])
  4. 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

const octokit = new Octokit({
  log: require("console-log-level")({ level: "info" }),
});

Hooks

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) {
    return findInCache(error.response.headers.etag);
  }

  throw error;
});
octokit.hook.wrap("request", async (request, options) => {
  // add logic before, after, catch errors or replace the request altogether
  return request(options);
});

See before-after-hook for more documentation on hooks.

Plugins

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:

  1. the current instance
  2. the options passed to the constructor.

In order to extend octokit's API, the plugin must return an object with the new methods.

// index.js
const { Octokit } = require("@octokit/core")
const MyOctokit = Octokit.plugin(
  require("./lib/my-plugin"),
  require("octokit-plugin-example")
);

const octokit = new MyOctokit({ greeting: "Moin moin" });
octokit.helloWorld(); // logs "Moin moin, world!"
octokit.request("GET /"); // logs "GET / - 200 in 123ms"

// lib/my-plugin.js
module.exports = (octokit, options = { greeting: "Hello" }) => {
  // hook into the request lifecycle
  octokit.hook.wrap("request", async (request, options) => {
    const time = Date.now();
    const response = await request(options);
    console.log(
      `${options.method} ${options.url} – ${response.status} in ${Date.now() -
        time}ms`
    );
    return response;
  });

  // add a custom method
  return {
    helloWorld: () => console.log(`${options.greeting}, world!`);
  }
};

Build your own Octokit with Plugins and Defaults

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");
const MyActionOctokit = Octokit.plugin(
  require("@octokit/plugin-paginate-rest").paginateRest,
  require("@octokit/plugin-throttling").throttling,
  require("@octokit/plugin-retry").retry
).defaults({
  throttle: {
    onAbuseLimit: (retryAfter, options) => {
      /* ... */
    },
    onRateLimit: (retryAfter, options) => {
      /* ... */
    },
  },
  authStrategy: require("@octokit/auth-action").createActionAuth,
  userAgent: `my-octokit-action/v1.2.3`,
});

const octokit = new MyActionOctokit();
const installations = await octokit.paginate("GET /app/installations");

LICENSE

MIT

More Repositories

1

octokit.js

The all-batteries-included GitHub SDK for Browsers, Node.js, and Deno.
TypeScript
6,695
star
2

octokit.rb

Ruby toolkit for the GitHub API
Ruby
3,818
star
3

octokit.net

A GitHub API client library for .NET
C#
2,591
star
4

octokit.objc

GitHub API client for Objective-C
Objective-C
1,841
star
5

rest.js

GitHub REST API client for JavaScript
JavaScript
503
star
6

graphql.js

GitHub GraphQL API client for browsers and Node
TypeScript
446
star
7

request-action

A GitHub Action to send arbitrary requests to GitHub's REST API
JavaScript
350
star
8

authentication-strategies.js

GitHub API authentication strategies for Browsers, Node.js, and Deno
320
star
9

webhooks.js

GitHub webhook events toolset for Node.js
TypeScript
296
star
10

go-octokit

Simple Go wrapper for the GitHub API
Go
257
star
11

request.js

Send parameterized requests to GitHub’s APIs with sensible defaults in browsers and Node
TypeScript
223
star
12

webhooks

machine-readable, always up-to-date GitHub Webhooks specifications
TypeScript
202
star
13

action.js

GitHub API client for GitHub Actions
TypeScript
173
star
14

graphql-schema

GitHub’s GraphQL Schema with validation. Automatically updated.
JavaScript
170
star
15

app.js

GitHub Apps toolset for Node.js
TypeScript
149
star
16

auth-app.js

GitHub App authentication for JavaScript
TypeScript
142
star
17

octokit.graphql.net

A GitHub GraphQL client library for .NET
C#
140
star
18

graphql-action

A GitHub Action to send queries to GitHub's GraphQL API
JavaScript
114
star
19

types.ts

Shared TypeScript definitions for Octokit projects
TypeScript
113
star
20

plugin-throttling.js

Octokit plugin for GitHub’s recommended request throttling
TypeScript
100
star
21

plugin-rest-endpoint-methods.js

Octokit plugin adding one method for all of api.github.com REST API endpoints
TypeScript
100
star
22

fixtures

Fixtures for all the octokittens
JavaScript
98
star
23

auth-token.js

GitHub API token authentication for browsers and Node.js
TypeScript
94
star
24

routes

machine-readable, always up-to-date GitHub REST API route specifications
JavaScript
84
star
25

oauth-app.js

GitHub OAuth toolset for Node.js
TypeScript
74
star
26

auth-oauth-app.js

GitHub OAuth App authentication for JavaScript
TypeScript
64
star
27

endpoint.js

Turns REST API endpoints into generic request options
TypeScript
54
star
28

go-sdk

A generated Go SDK from GitHub's OpenAPI specification.
Go
51
star
29

webhooks.net

GitHub webhook events toolset for .NET
C#
46
star
30

plugin-paginate-rest.js

Octokit plugin to paginate REST API endpoint responses
TypeScript
45
star
31

dotnet-sdk

C#
43
star
32

octopoller.rb

A micro gem for polling and retrying. Perfect for making repeating requests.
Ruby
43
star
33

auth-action.js

GitHub API token authentication for GitHub Actions
TypeScript
38
star
34

openapi

GitHub's official OpenAPI spec with Octokit extensions
JavaScript
38
star
35

openapi-types.ts

Generated TypeScript definitions based on GitHub's OpenAPI spec
JavaScript
37
star
36

plugin-paginate-graphql.js

Octokit plugin to paginate GraphQL Query responses
TypeScript
31
star
37

plugin-retry.js

Octokit plugin for GitHub’s recommended request retries
TypeScript
29
star
38

fixtures-server

Fixtures server for browser & language agnositic octokit testing
JavaScript
26
star
39

webhooks-methods.js

Methods to handle GitHub Webhook requests
TypeScript
20
star
40

plugin-enterprise-server.js

Octokit plugin for GitHub Enterprise REST APIs
TypeScript
19
star
41

octokit-next.js

JavaScript
18
star
42

oauth-authorization-url.js

Universal library to retrieve GitHub’s identity URL for the OAuth web flow
TypeScript
16
star
43

auth-oauth-user-client.js

OAuth user authentication without exposing client secret
15
star
44

create-octokit-project.js

"npm init" script to create a new Octokit JS module
JavaScript
15
star
45

auth-oauth-user.js

Octokit authentication strategy for OAuth clients
TypeScript
15
star
46

plugin-create-or-update-text-file.js

Convenience method to create/edit/delete a text file based on its current content
TypeScript
13
star
47

app-permissions

machine-readable, always up-to-date GitHub App permissions
JavaScript
10
star
48

auth-oauth-device.js

GitHub OAuth Device authentication strategy for JavaScript
TypeScript
10
star
49

request-error.js

Error class for Octokit request errors
TypeScript
9
star
50

handbook

Handbook for Octokit maintainers and GitHub integrators
9
star
51

auth-basic.js

GitHub API Basic authentication for browsers and Node.js
TypeScript
8
star
52

.github

7
star
53

discussions

discussions and planning for Octokit clients
7
star
54

plugin-request-log.js

Log all requests and request errors
TypeScript
7
star
55

source-generator

Go
6
star
56

plugin-enterprise-cloud.js

Octokit plugin for GitHub Enterprise Cloud REST APIs
TypeScript
6
star
57

tsconfig

TypeScript configuration for Octokit packages
JavaScript
5
star
58

oauth-methods.js

Request methods to create and refresh user access tokens for OAuth and GitHub Apps
TypeScript
4
star
59

auth-callback.js

GitHub API authentication using a callback method
TypeScript
4
star
60

auth-unauthenticated.js

strategy for explicitly unauthenticated Octokit instances
TypeScript
4
star
61

tf-acc-test-empty-f89p1

Terraform acceptance test f89p1
2
star
62

plugin-enterprise-compatibility.js

Octokit plugin for improving GHE compatibility
TypeScript
1
star
63

openapi-webhooks

JavaScript
1
star