Gathering detailed insights and metrics for @octokit/request
Gathering detailed insights and metrics for @octokit/request
Gathering detailed insights and metrics for @octokit/request
Gathering detailed insights and metrics for @octokit/request
@octokit/request-error
Error class for Octokit request errors
@octokit-next/request
Simplified version of `@octokit/request` to experiment with ESM and types
@octokit-next/request-error
Error class for Octokit request errors
@octokit/plugin-request-log
Log all requests and request errors
Send parameterized requests to GitHub’s APIs with sensible defaults in browsers and Node
npm install @octokit/request
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
231 Stars
710 Commits
60 Forks
27 Watching
8 Branches
35 Contributors
Updated on 26 Nov 2024
TypeScript (97.87%)
JavaScript (2.13%)
Cumulative downloads
Total Downloads
Last day
-0.3%
2,198,279
Compared to previous day
Last week
6.3%
11,968,613
Compared to previous week
Last month
10.6%
48,047,227
Compared to previous month
Last year
26%
463,014,143
Compared to previous year
Send parameterized requests to GitHub’s APIs with sensible defaults in browsers and Node
@octokit/request
is a request library for browsers & node that makes it easier
to interact with GitHub’s REST API and
GitHub’s GraphQL API.
It uses @octokit/endpoint
to parse
the passed options and sends the request using fetch. You can pass a custom fetch
function using the options.request.fetch
option, see below.
🤩 1:1 mapping of REST API endpoint documentation, e.g. Add labels to an issue becomes
1request("POST /repos/{owner}/{repo}/issues/{number}/labels", { 2 mediaType: { 3 previews: ["symmetra"], 4 }, 5 owner: "octokit", 6 repo: "request.js", 7 number: 1, 8 labels: ["🐛 bug"], 9});
👶 Small bundle size (<4kb minified + gzipped)
😎 Authenticate with any of GitHubs Authentication Strategies.
👍 Sensible defaults
baseUrl
: https://api.github.com
headers.accept
: application/vnd.github.v3+json
headers['user-agent']
: octokit-request.js/<current version> <OS information>
, e.g. octokit-request.js/1.2.3 Node.js/10.15.0 (macOS Mojave; x64)
👌 Simple to test: mock requests by passing a custom fetch method.
🧐 Simple to debug: Sets error.request
to request options causing the error (with redacted credentials).
Browsers |
Load @octokit/request directly from esm.sh
|
---|---|
Node |
Install with
|
1// Following GitHub docs formatting: 2// https://developer.github.com/v3/repos/#list-organization-repositories 3const result = await request("GET /orgs/{org}/repos", { 4 headers: { 5 authorization: "token 0000000000000000000000000000000000000001", 6 }, 7 org: "octokit", 8 type: "private", 9}); 10 11console.log(`${result.data.length} repos found.`);
For GraphQL request we recommend using @octokit/graphql
1const result = await request("POST /graphql", { 2 headers: { 3 authorization: "token 0000000000000000000000000000000000000001", 4 }, 5 query: `query ($login: String!) { 6 organization(login: $login) { 7 repositories(privacy: PRIVATE) { 8 totalCount 9 } 10 } 11 }`, 12 variables: { 13 login: "octokit", 14 }, 15});
method
& url
as part of optionsAlternatively, pass in a method and a url
1const result = await request({ 2 method: "GET", 3 url: "/orgs/{org}/repos", 4 headers: { 5 authorization: "token 0000000000000000000000000000000000000001", 6 }, 7 org: "octokit", 8 type: "private", 9});
The simplest way to authenticate a request is to set the Authorization
header directly, e.g. to a personal access token.
1const requestWithAuth = request.defaults({ 2 headers: { 3 authorization: "token 0000000000000000000000000000000000000001", 4 }, 5}); 6const result = await requestWithAuth("GET /user");
For more complex authentication strategies such as GitHub Apps or Basic, we recommend the according authentication library exported by @octokit/auth
.
1import { createAppAuth } from "@octokit/auth-app"; 2const auth = createAppAuth({ 3 appId: process.env.APP_ID, 4 privateKey: process.env.PRIVATE_KEY, 5 installationId: 123, 6}); 7const requestWithAuth = request.defaults({ 8 request: { 9 hook: auth.hook, 10 }, 11 mediaType: { 12 previews: ["machine-man"], 13 }, 14}); 15 16const { data: app } = await requestWithAuth("GET /app"); 17const { data: app } = await requestWithAuth( 18 "POST /repos/{owner}/{repo}/issues", 19 { 20 owner: "octocat", 21 repo: "hello-world", 22 title: "Hello from the engine room", 23 }, 24);
request(route, options)
or request(options)
.
Options
name | type | description |
---|---|---|
route
| String |
**Required**. If route is set it has to be a string consisting of the request method and URL, e.g. GET /orgs/{org}
|
options.baseUrl
| String |
The base URL that route or url will be prefixed with, if they use relative paths. Defaults to https://api.github.com .
|
options.headers
| Object |
Custom headers. Passed headers are merged with defaults:headers['user-agent'] defaults to octokit-rest.js/1.2.3 (where 1.2.3 is the released version).headers['accept'] defaults to application/vnd.github.v3+json .Use options.mediaType.{format,previews} to request API previews and custom media types.
|
options.method
| String |
Any supported http verb, case-insensitive. Defaults to Get .
|
options.mediaType.format
| String | Media type param, such as `raw`, `html`, or `full`. See Media Types. |
options.mediaType.previews
| Array of strings | Name of previews, such as `mercy`, `symmetra`, or `scarlet-witch`. See GraphQL Schema Previews. Note that these only apply to GraphQL requests and have no effect on REST routes. |
options.url
| String |
**Required**. A path or full URL which may contain :variable or {variable} placeholders,
e.g. /orgs/{org}/repos . The url is parsed using url-template.
|
options.data
| Any | Set request body directly instead of setting it to JSON based on additional parameters. See "The `data` parameter" below. |
options.request.fetch
| Function | Custom replacement for fetch. Useful for testing or request hooks. |
options.request.hook
| Function |
Function with the signature hook(request, endpointOptions) , where endpointOptions are the parsed options as returned by endpoint.merge() , and request is request() . This option works great in conjunction with before-after-hook.
|
options.request.signal
| new AbortController().signal |
Use an AbortController instance to cancel a request. In node you can only cancel streamed requests.
|
options.request.log
|
object
|
Used for internal logging. Defaults to console .
|
options.request.parseSuccessResponseBody
|
boolean
|
If set to false the returned `response` will be passed through from `fetch`. This is useful to stream response.body when downloading files from the GitHub API.
|
All other options except options.request.*
will be passed depending on the method
and url
options.
url
, it will be used as replacement. For example, if the passed options are {url: '/orgs/{org}/repos', org: 'foo'}
the returned options.url
is https://api.github.com/orgs/foo/repos
method
is GET
or HEAD
, the option is passed as query parameterResult
request
returns a promise. If the request was successful, the promise resolves with an object containing 4 keys:
key | type | description |
---|---|---|
status | Integer | Response status status |
url | String | URL of response. If a request results in redirects, this is the final URL. You can send a HEAD request to retrieve it without loading the full response body. |
headers | Object | All response headers |
data | Any | The response body as returned from server. If the response is JSON then it will be parsed into an object |
If an error occurs, the promise is rejected with an error
object containing 3 keys to help with debugging:
error.status
The http response status codeerror.request
The request options such as method
, url
and data
error.response
The http response object with url
, headers
, and data
If the error is due to an AbortSignal
being used, the resulting AbortError
is bubbled up to the caller.
request.defaults()
Override or set default options. Example:
1import { request } from "@octokit/request"; 2const myrequest = request.defaults({ 3 baseUrl: "https://github-enterprise.acme-inc.com/api/v3", 4 headers: { 5 "user-agent": "myApp/1.2.3", 6 authorization: `token 0000000000000000000000000000000000000001`, 7 }, 8 org: "my-project", 9 per_page: 100, 10}); 11 12myrequest(`GET /orgs/{org}/repos`);
You can call .defaults()
again on the returned method, the defaults will cascade.
1const myProjectRequest = request.defaults({ 2 baseUrl: "https://github-enterprise.acme-inc.com/api/v3", 3 headers: { 4 "user-agent": "myApp/1.2.3", 5 }, 6 org: "my-project", 7}); 8const myProjectRequestWithAuth = myProjectRequest.defaults({ 9 headers: { 10 authorization: `token 0000000000000000000000000000000000000001`, 11 }, 12});
myProjectRequest
now defaults the baseUrl
, headers['user-agent']
,
org
and headers['authorization']
on top of headers['accept']
that is set
by the global default.
request.endpoint
See https://github.com/octokit/endpoint.js. Example
1const options = request.endpoint("GET /orgs/{org}/repos", { 2 org: "my-project", 3 type: "private", 4}); 5 6// { 7// method: 'GET', 8// url: 'https://api.github.com/orgs/my-project/repos?type=private', 9// headers: { 10// accept: 'application/vnd.github.v3+json', 11// authorization: 'token 0000000000000000000000000000000000000001', 12// 'user-agent': 'octokit/endpoint.js v1.2.3' 13// } 14// }
All of the @octokit/endpoint
API can be used:
octokitRequest.endpoint()
octokitRequest.endpoint.defaults()
octokitRequest.endpoint.merge()
octokitRequest.endpoint.parse()
data
parameter – set request body directlySome endpoints such as Render a Markdown document in raw mode don’t have parameters that are sent as request body keys, instead the request body needs to be set directly. In these cases, set the data
parameter.
1const response = await request("POST /markdown/raw", { 2 data: "Hello world github/linguist#1 **cool**, and #1!", 3 headers: { 4 accept: "text/html;charset=utf-8", 5 "content-type": "text/plain", 6 }, 7}); 8 9// Request is sent as 10// 11// { 12// method: 'post', 13// url: 'https://api.github.com/markdown/raw', 14// headers: { 15// accept: 'text/html;charset=utf-8', 16// 'content-type': 'text/plain', 17// 'user-agent': userAgent 18// }, 19// body: 'Hello world github/linguist#1 **cool**, and #1!' 20// } 21// 22// not as 23// 24// { 25// ... 26// body: '{"data": "Hello world github/linguist#1 **cool**, and #1!"}' 27// }
There are API endpoints that accept both query parameters as well as a body. In that case you need to add the query parameters as templates to options.url
, as defined in the RFC 6570 URI Template specification.
Example
1request( 2 "POST https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets{?name,label}", 3 { 4 name: "example.zip", 5 label: "short description", 6 headers: { 7 "content-type": "text/plain", 8 "content-length": 14, 9 authorization: `token 0000000000000000000000000000000000000001`, 10 }, 11 data: "Hello, world!", 12 }, 13);
The way to pass a custom Agent
to requests is by creating a custom fetch
function and pass it as options.request.fetch
. A good example can be undici's fetch
implementation.
Example (See example in CodeSandbox)
1import { request } from "@octokit/request"; 2import { fetch as undiciFetch, Agent } from "undici"; 3 4/** @type {typeof import("undici").fetch} */ 5const myFetch = (url, options) => { 6 return undiciFetch(url, { 7 ...options, 8 dispatcher: new Agent({ 9 keepAliveTimeout: 10, 10 keepAliveMaxTimeout: 10, 11 }), 12 }); 13}; 14 15const { data } = await request("GET /users/{username}", { 16 username: "octocat", 17 headers: { 18 "X-GitHub-Api-Version": "2022-11-28", 19 }, 20 options: { 21 request: { 22 fetch: myFetch, 23 }, 24 }, 25});
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
all changesets reviewed
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
SAST tool is run on all commits
Details
Reason
security policy file detected
Details
Reason
1 existing vulnerabilities detected
Details
Reason
7 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 6
Reason
dependency not pinned by hash detected -- score normalized to 4
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More