{"id":13236,"library":"github-api","title":"github-api wrapper (Github.js)","description":"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.","status":"active","version":"3.4.0","language":"javascript","source_language":"en","source_url":"git://github.com/github-tools/github","tags":["javascript","github","api"],"install":[{"cmd":"npm install github-api","lang":"bash","label":"npm"},{"cmd":"yarn add github-api","lang":"bash","label":"yarn"},{"cmd":"pnpm add github-api","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core HTTP client for making requests to the GitHub API. Vulnerabilities in Axios (CVEs) have led to critical security updates in `github-api`.","package":"axios"}],"imports":[{"note":"The primary class is exported as a default export, not a named export, when using ES Modules.","wrong":"import { GitHub } from 'github-api';","symbol":"GitHub","correct":"import GitHub from 'github-api';"},{"note":"For CommonJS environments, `require('github-api')` directly returns the `GitHub` class.","wrong":"const { GitHub } = require('github-api');","symbol":"GitHub (CommonJS)","correct":"const GitHub = require('github-api');"},{"note":"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.","wrong":"import { getGist } from 'github-api';","symbol":"Service instances (e.g., Gist, User)","correct":"const gh = new GitHub({ token: '...' });\nconst gist = gh.getGist();\nconst user = gh.getUser();"}],"quickstart":{"code":"import GitHub from 'github-api';\n\n// It's recommended to use an environment variable for your GitHub Personal Access Token.\n// Create one at: https://github.com/settings/tokens\nconst GITHUB_TOKEN = process.env.GITHUB_TOKEN ?? ''; \n\nif (!GITHUB_TOKEN) {\n  console.warn(\"WARNING: GITHUB_TOKEN environment variable not set. Some authenticated operations might fail.\");\n  console.warn(\"Please set GITHUB_TOKEN for full functionality (e.g., 'export GITHUB_TOKEN=YOUR_TOKEN').\");\n}\n\n// Authenticated client using a personal access token\nconst gh = new GitHub({\n  token: GITHUB_TOKEN\n});\n\nasync function createAndReadGist() {\n  try {\n    const gistService = gh.getGist(); // Service for Gist operations\n\n    // Create a new public gist\n    const { data: createdGist } = await gistService.create({\n      public: true,\n      description: 'My first gist created with github-api',\n      files: {\n        \"hello.ts\": {\n          content: \"console.log('Hello from github-api gist!');\"\n        },\n        \"config.json\": {\n          content: JSON.stringify({ version: \"1.0.0\", env: \"development\" }, null, 2)\n        }\n      }\n    });\n\n    console.log(`Gist created successfully: ${createdGist.html_url}`);\n    console.log(`Gist ID: ${createdGist.id}`);\n\n    // Read the created gist using its ID\n    const { data: retrievedGist } = await gistService.read(createdGist.id);\n    console.log(\"\\nRetrieved Gist content:\");\n    for (const file in retrievedGist.files) {\n      console.log(`--- ${file} ---`);\n      console.log(retrievedGist.files[file].content);\n    }\n\n    // Example: List the first 3 files in the gist\n    console.log(`\\nFirst 3 files in gist ${retrievedGist.id}:`);\n    Object.keys(retrievedGist.files).slice(0, 3).forEach(filename => {\n        console.log(`- ${filename}`);\n    });\n\n    // Optional: Delete the gist to clean up after testing\n    // await gistService.delete(createdGist.id);\n    // console.log(`Gist ${createdGist.id} deleted.`);\n\n  } catch (error: any) {\n    console.error(\"\\nAn error occurred during Gist operations:\", error.message);\n    if (error.response) {\n        console.error(\"GitHub API Response Status:\", error.response.status);\n        console.error(\"GitHub API Response Data:\", error.response.data);\n    }\n  }\n}\n\nasync function listUserRepos() {\n    try {\n        if (!GITHUB_TOKEN) {\n            console.log(\"\\nSkipping user repository listing: GITHUB_TOKEN not set.\");\n            return;\n        }\n        const userService = gh.getUser(); // Represents the authenticated user\n        const { data: repos } = await userService.listRepos();\n        console.log(`\\nAuthenticated user's repositories (first 3 of ${repos.length}):`);\n        repos.slice(0, 3).forEach((repo: any) => console.log(`- ${repo.name}`));\n        if (repos.length > 3) console.log(\"...\");\n    } catch (error: any) {\n        console.error(\"\\nError listing user repos:\", error.message);\n        if (error.response) {\n            console.error(\"GitHub API Response Status:\", error.response.status);\n            console.error(\"GitHub API Response Data:\", error.response.data);\n        }\n    }\n}\n\ncreateAndReadGist();\nlistUserRepos();\n","lang":"typescript","description":"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."},"warnings":[{"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 }`.","message":"Major 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.","severity":"breaking","affected_versions":">=3.0.0"},{"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`.","message":"The 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.","severity":"breaking","affected_versions":"<3.2.1"},{"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 */ })`.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"Many 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).","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=3.4.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","cause":"Attempting to access a protected GitHub API resource without providing valid authentication credentials or with insufficient scopes.","error":"Error: Request failed with status code 401"},{"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.","cause":"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.","error":"TypeError: Cannot read properties of undefined (reading 'then')"},{"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.","cause":"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).","error":"Error: Request failed with status code 403"},{"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';`.","cause":"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.","error":"ReferenceError: GitHub is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}