Registry / communication / github-api

github-api

JSON →
library0.1jsnpmunverified

github-api (also known as Github.js) is a higher-level JavaScript wrapper for the GitHub API. It provides a more convenient, object-oriented interface over raw HTTP requests. The library, currently at version 3.4.0, offers dual support for both traditional callback-based APIs (as seen in versions prior to 1.0) and modern Promise-based APIs, with the latter returning raw Axios request promises for greater flexibility. Its release cadence is driven by bug fixes, new API feature implementations (like `getCombinedStatus` and `listCommitsOnPR`), and crucial security updates. It aims to abstract the complexities of direct GitHub API interactions while remaining compatible with both Node.js (LTS and current versions) and browser environments, offering a key differentiator through its flexible API consumption patterns and direct Axios promise exposure.

npm install github-api
INSTALL
IMPORT
SIG · GITHUB-API
G
github-api
communicationjavascriptv0.1
Install
—
Import
—
Disk
—
Pass rate
0/ 6
Env Coverage0 / 6
glibc
18–22
musl
18–22
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18–226 runs
build_error
glibc
node 18–226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

GitHub
✓ import GitHub from 'github-api';
✗ import { GitHub } from 'github-api';
The primary class is exported as a default export, not a named export, when using ES Modules.
GitHub (CommonJS)
✓ const GitHub = require('github-api');
✗ const { GitHub } = require('github-api');
For CommonJS environments, `require('github-api')` directly returns the `GitHub` class.
Service instances (e.g., Gist, User)
✓ const gh = new GitHub({ token: '...' }); const gist = gh.getGist(); const user = gh.getUser();
✗ import { getGist } from 'github-api';
Individual API services (like `getGist`, `getUser`, `getRepo`) are methods on an instantiated `GitHub` object, not directly importable from the package root. You must first create a `GitHub` instance.

This quickstart demonstrates how to instantiate the GitHub client, authenticate with a personal access token, create and read a public gist, and list the authenticated user's repositories using the modern Promise-based API with async/await. It includes error handling and highlights the use of environment variables for sensitive credentials.

import GitHub from 'github-api'; // It's recommended to use an environment variable for your GitHub Personal Access Token. // Create one at: https://github.com/settings/tokens const GITHUB_TOKEN = process.env.GITHUB_TOKEN ?? ''; if (!GITHUB_TOKEN) { console.warn("WARNING: GITHUB_TOKEN environment variable not set. Some authenticated operations might fail."); console.warn("Please set GITHUB_TOKEN for full functionality (e.g., 'export GITHUB_TOKEN=YOUR_TOKEN')."); } // Authenticated client using a personal access token const gh = new GitHub({ token: GITHUB_TOKEN }); async function createAndReadGist() { try { const gistService = gh.getGist(); // Service for Gist operations // Create a new public gist const { data: createdGist } = await gistService.create({ public: true, description: 'My first gist created with github-api', files: { "hello.ts": { content: "console.log('Hello from github-api gist!');" }, "config.json": { content: JSON.stringify({ version: "1.0.0", env: "development" }, null, 2) } } }); console.log(`Gist created successfully: ${createdGist.html_url}`); console.log(`Gist ID: ${createdGist.id}`); // Read the created gist using its ID const { data: retrievedGist } = await gistService.read(createdGist.id); console.log("\nRetrieved Gist content:"); for (const file in retrievedGist.files) { console.log(`--- ${file} ---`); console.log(retrievedGist.files[file].content); } // Example: List the first 3 files in the gist console.log(`\nFirst 3 files in gist ${retrievedGist.id}:`); Object.keys(retrievedGist.files).slice(0, 3).forEach(filename => { console.log(`- ${filename}`); }); // Optional: Delete the gist to clean up after testing // await gistService.delete(createdGist.id); // console.log(`Gist ${createdGist.id} deleted.`); } catch (error: any) { console.error("\nAn error occurred during Gist operations:", error.message); if (error.response) { console.error("GitHub API Response Status:", error.response.status); console.error("GitHub API Response Data:", error.response.data); } } } async function listUserRepos() { try { if (!GITHUB_TOKEN) { console.log("\nSkipping user repository listing: GITHUB_TOKEN not set."); return; } const userService = gh.getUser(); // Represents the authenticated user const { data: repos } = await userService.listRepos(); console.log(`\nAuthenticated user's repositories (first 3 of ${repos.length}):`); repos.slice(0, 3).forEach((repo: any) => console.log(`- ${repo.name}`)); if (repos.length > 3) console.log("..."); } catch (error: any) { console.error("\nError listing user repos:", error.message); if (error.response) { console.error("GitHub API Response Status:", error.response.status); console.error("GitHub API Response Data:", error.response.data); } } } createAndReadGist(); listUserRepos();
Debug
Known issues
breakingMajor version `v3.0.0` likely introduced breaking changes to API return types and error handling, shifting towards promise-based responses which return raw Axios request promises. While specific breaking changes are not explicitly detailed in the changelog, major version bumps typically signify such alterations. Code written for older callback-centric versions (e.g., `< v1.0`) will need significant updates to handle the modern promise-based paradigm or adjusted callback signatures.
fix
Review API documentation for specific methods. Transition from raw callbacks to `.then().catch()` or `async/await` for most operations. Be prepared to handle Axios response objects directly, as method calls now return raw promises containing `{ data, status, headers, config }`.
affects: >=3.0.0
breakingThe library fixed a critical Axios CVE related to Server-Side Request Forgery (SSRF) and credential leakage. Older versions using Axios 0.19.x or earlier are vulnerable. Update to `github-api@3.2.1` or `github-api@3.4.0` or newer to mitigate this.
fix
Upgrade to `github-api@3.2.1` or `github-api@3.4.0` (or the latest stable version) immediately. Ensure your `package.json` specifies a secure version range for `github-api` and `axios`.
affects: <3.2.1
gotchaThe library supports both callback and promise-based APIs. Mixing these paradigms (e.g., trying to use `.then()` on a method designed for callbacks, or expecting a direct return value from an async function) will lead to unexpected behavior or errors. The promise-based API returns a raw Axios promise, requiring users to destructure the `{ data }` property for the actual GitHub API response payload.
fix
Consistently use either callbacks or promises for API calls within your codebase. When using promises, always handle the `{ data }` object from the Axios response: `someMethod().then(({ data }) => { /* use data */ })`.
affects: >=1.0.0
gotchaMany GitHub API operations, especially those involving user data or modifying resources (e.g., creating gists, managing repositories), require authentication. Failing to provide valid credentials (token, username/password) will result in 4xx HTTP errors (e.g., 401 Unauthorized, 403 Forbidden, or even 404 Not Found for private resources to prevent enumeration).
fix
Always initialize `GitHub` with appropriate authentication: `new GitHub({ token: 'YOUR_PAT' })`. Ensure your Personal Access Token (PAT) has the necessary scopes for the operations you are performing. Avoid hardcoding credentials; use environment variables or a secure configuration management system.
affects: >=1.0.0
gotchaThe project is explicitly looking for maintainers. While currently active with recent fixes, future maintenance and feature development could slow down or become inconsistent if new maintainers are not found. This might lead to slower adoption of new GitHub API features or delayed security patches.
fix
Monitor the project's GitHub repository for updates on maintainership. Consider contributing or preparing for alternative GitHub API clients in the long term, such as Octokit.js, which is officially maintained by GitHub.
affects: >=3.4.0
Errors
Common errors & fixes
Error: Request failed with status code 401
Attempting to access a protected GitHub API resource without providing valid authentication credentials or with insufficient scopes.
fix
Ensure your `GitHub` instance is initialized with a Personal Access Token (PAT): `new GitHub({ token: 'YOUR_PAT' })`. Verify that the PAT has the required scopes (permissions) for the specific API call you are making.
TypeError: Cannot read properties of undefined (reading 'then')
Occurs when attempting to use `.then()` on a method that implicitly or explicitly returns `undefined` because it's expecting a callback, or if the `GitHub` object or its service method (e.g., `gh.getGist()`) was not correctly instantiated.
fix
Confirm the method you are calling is indeed promise-based. If it's callback-based, pass a callback function. If it's promise-based, ensure the `GitHub` object and its service methods are correctly instantiated before calling methods on them.
Error: Request failed with status code 403
Often indicates exceeding GitHub API rate limits, or attempting an action that is forbidden even with authentication due to specific permissions (e.g., trying to write to a repository you only have read access to).
fix
Check the `x-ratelimit-remaining` and `x-ratelimit-reset` headers in the response for rate limit information and wait until the reset time. Review your PAT's scopes to ensure it has all necessary permissions for the operation. If persistently blocked, consider using GitHub Apps for higher rate limits or more granular permissions.
ReferenceError: GitHub is not defined
This error typically occurs in a Node.js (CommonJS) environment if you try to `import GitHub from 'github-api'` without proper ESM setup, or if the module hasn't been `require()`d or imported correctly in the scope.
fix
For CommonJS, use `const GitHub = require('github-api');`. For ES Modules, ensure your project is configured for ESM (`"type": "module"` in `package.json`) and use `import GitHub from 'github-api';`.
Upgrade
Version history
0.1latest on npm
Audit
Dependencies
axiosrequiredCore HTTP client for making requests to the GitHub API. Vulnerabilities in Axios (CVEs) have led to critical security updates in `github-api`.
Agent activity
18 hits · last 30 days
node
16
Amazon
1
OpenAI (training)
1
Resources
github-api — npm install github-api · libregistry