Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

GitHub REST API client for JavaScript

License

NotificationsYou must be signed in to change notification settings

Rebeldesigns-net/rest.js

 
 

GitHub REST API client for JavaScript

@latestBuild StatusCoverage StatusGreenkeeper

Usage

Node

Install withnpm install @octokit/rest.

constOctokit=require('@octokit/rest')constoctokit=newOctokit()// Compare: https://developer.github.com/v3/repos/#list-organization-repositoriesoctokit.repos.listForOrg({org:'octokit',type:'public'}).then(({ data, status, headers})=>{// handle data})

Browser

  1. Downloadoctokit-rest.min.js from the latest release:https://github.com/octokit/rest.js/releases

  2. Load it as script into your web application:

    <scriptsrc="octokit-rest.min.js"></script>
  3. Initializeoctokit

    constoctokit=newOctokit()// Compare: https://developer.github.com/v3/repos/#list-organization-repositoriesoctokit.repos.listForOrg({org:'octokit',type:'public'}).then(({data, headers, status})=>{// handle data})

Client options

All available client options with default values

constOctokit=require('@octokit/rest')constoctokit=newOctokit({// see "Authentication" section belowauth:undefined,// setting a user agent is required: https://developer.github.com/v3/#user-agent-required// v1.2.3 will be current @octokit/rest versionuserAgent:'octokit/rest.js v1.2.3',// add list of previews you’d like to enable globally,// see https://developer.github.com/v3/previews/.// Example: ['jean-grey', 'symmetra']previews:[],// set custom URL for on-premise GitHub Enterprise installationsbaseUrl:'https://api.github.com',// pass custom methods for debug, info, warn and errorlog:{debug:()=>{},info:()=>{},warn:console.warn,error:console.error},request:{// Node.js only: advanced request options can be passed as http(s) agent,// such as custom SSL certificate or proxy settings.// See https://nodejs.org/api/http.html#http_class_http_agentagent:undefined,// request timeout in ms. 0 means no timeouttimeout:0}})

Authentication

Most GitHub API calls don't require authentication. Generally:

  1. If you can see the information by visiting the site without being logged in, you don't have to be authenticated to retrieve the same information through the API.
  2. If you want to change data, you have to be authenticated.

To enable authenticated requests,get a token in your GitHub profile's Developer Settings. Then, pass anauth option to the Octokit constructor:

constclientWithAuth=newOctokit({auth:'token secret123'})

Theauth option can be:

  1. A string

    The value will be passed as value for theAuthorization header,seeauthentication.

    newOctokit({auth:'secret123'})

    Use this for

    • personal access tokens
    • OAuth access tokens
    • GitHub App bearer tokens
    • GitHub App installation tokens
  2. As object with the propertiesusername,password,on2fa.

    on2fa is an asynchronous function that must resolve with two-factorauthentication code sent to the user.

    newOctokit({auth:{username:'octocat',password:'secret',asyncon2fa(){// example: ask the userreturnprompt('Two-factor authentication Code:')}}})
  3. An object with the propertiesclientId andclientSecret

    OAuth applications can authenticate using theirclientId andclientSecretin order toincrease the unauthenticated rate limit.

  4. A function

    Must resolve with a string which then will be passed as value for theAuthorization header. The function will be called before each request andcan be asynchronous.

    newOctokit({auth(){return'secret123'}})

    This is useful for GitHub apps, as installations need to renew their tokens each hour.Here is an example on how to implement authentication for GitHub Apps

    constApp=require('@octokit/app')constOctokit=require('@octokit/rest')constapp=newApp({id:process.env.APP_ID,privateKey:process.env.PRIVATE_KEY})constoctokit=newOctokit({auth:()=>app.getInstallationAccessToken({installationId:process.env.INSTALLATION_ID})})

    See also:https://github.com/octokit/app.js#authenticating-as-an-installation.

API docs

Find all APIs documented athttps://octokit.github.io/rest.js/.

API Previews

To enable any ofGitHub’s API Previews,pass thepreviews option to the GitHub constructor

constoctokit=newOctokit({previews:['mercy-preview']})

If you want to enable one or multiple previews for a single request, set themediaType.preview option

const{data:{ topics}}=awaitoctokit.repos.get({owner:'octokit',repo:'rest.js',mediaType:{previews:['symmetra']}})

Request formats

Some API endpoints support alternative response formats, seeMedia types.

For example, to request apull request as diff format, set themediaType.format option

const{data:prDiff}=awaitoctokit.pulls.get({owner:'octokit',repo:'rest.js',number:1278,mediaType:{format:'diff'}})

Custom requests

To send custom requests you can use the lower-leveloctokit.request() method

octokit.request('GET /')

ThebaseUrl, headers and other defaults are already set. For more informationon theoctokit.request() API see@octokit/request

All the endpoint methods such asoctokit.repos.get() are aliases ofoctokit.request()with pre-bound default options. So you can use the@octokit/request API toget the default options or get generic request option to use with your preferredrequest library.

constdefaultOptions=octokit.repos.get.endpoint.DEFAULTSconstrequestOptions=octokit.repos.get.endpoint()

Pagination

All endpoint methods starting with.list* do not return all responses at once but instead return the first 30 items by default, see alsoGitHub’s REST API pagination documentation.

To automatically receive all results across all pages, you can use theoctokit.paginate() method:

octokit.paginate('GET /repos/:owner/:repo/issues',{owner:'octokit',repo:'rest.js'}).then(issues=>{// issues is an array of all issue objects})

octokit.paginate() accepts the same options asoctokit.request(). You can optionally pass an additional function to map the results from each response. The map must return a new value, usually an array with mapped data.

octokit.paginate('GET /repos/:owner/:repo/issues',{owner:'octokit',repo:'rest.js'},response=>response.data.map(issue=>issue.title)).then(issueTitles=>{// issueTitles is now an array with the titles only})

To stop paginating early, you can call thedone() function passed as 2nd argument to the response map function. Note that you still have to return the value you want to map the response to, otherwise the last response will be mapped to undefined.

octokit.paginate('GET /organizations',(response,done)=>{if(response.data.find(issues=>issue.body.includes('something'))){done()}returnresponse.data})

To paginate responses for one of the registered endpoint methods such asoctokit.issues.listForRepo() you can use the.endpoint.merge() method registered for all endpoint methods:

constoptions=octokit.issues.listForRepo.endpoint.merge({owner:'octokit',repo:'rest.js'})octokit.paginate(options).then(issues=>{// issues is an array of all issue objects})

If your runtime environment supports async iterators (such as Node 10+), you can iterate through each response

forawait(constresponseofoctokit.paginate.iterator(options)){// do whatever you want with each response, break out of the loop, etc.}

octokit.paginate.iterator() accepts the same options asoctokit.paginate().

Hooks

You can customize Octokit’s request lifecycle with hooks. Available methods are

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)})

Seebefore-after-hook for moredocumentation on hooks.

Plugins

You can customize and extend Octokit’s functionality using plugins

// index.jsconstMyOctokit=require('@octokit/request').plugin([require('./lib/my-plugin'),require('octokit-plugin-example')])// lib/my-plugin.jsmodule.exports=(octokit,options={greeting:'Hello'})=>{// add a custom methodoctokit.helloWorld=()=>console.log(`${options.greeting}, world!`)// hook into the request lifecycleoctokit.hook.wrap('request',async(request,options)=>{consttime=Date.now()constresponse=awaitrequest(options)octokit.log.info(`${options.method}${options.url}${response.status} in${Date.now()-time}ms`)returnresponse})}

.plugin accepts a function or an array of functions.

We recommend usingOctokit’s log methods to help users of your plugin with debugging.

You can add new methods to theoctokit instance passed as the first argument tothe plugin function. The 2nd argument is the options object passed to theconstructor when instantiating theoctokit client.

constoctokit=newMyOctokit({greeting:'Hola'})octokit.helloWorld()// Hola, world!

Register custom endpoint methods

You can register custom endpoint methods such asoctokit.repos.get() usingtheoctokit.registerEndpoints(routes) method

octokit.registerEndpoints({foo:{bar:{method:'PATCH',url:'/repos/:owner/:repo/foo',headers:{accept:'application/vnd.github.foo-bar-preview+json'},params:{owner:{required:true,type:'string'},repo:{required:true,type:'string'},baz:{required:true,type:'string',enum:['qux','quux','quuz']}}}}})octokit.foo.bar({owner:'octokit',repo:'rest.js',baz:'quz'})

This is useful when you participate in private beta features and prefer theconvenience of methods for the new endpoints instead of usingoctokit.request().

Throttling

When you send too many requests in too little time you will likely hit errors due to quotas.

In order to automatically throttle requests as recommended in thebest practices for integrators, we recommend you install the@octokit/plugin-throttling plugin.

Thethrottle.onAbuseLimit andthrottle.onRateLimit options are required. Returntrue to automatically retry the request afterretryAfter seconds.

constOctokit=require('@octokit/rest').plugin(require('@octokit/plugin-throttling'))constoctokit=newOctokit({auth:'token '+process.env.TOKEN,throttle:{onRateLimit:(retryAfter,options)=>{octokit.log.warn(`Request quota exhausted for request${options.method}${options.url}`)if(options.request.retryCount===0){// only retries onceconsole.log(`Retrying after${retryAfter} seconds!`)returntrue}},onAbuseLimit:(retryAfter,options)=>{// does not retry, only logs a warningoctokit.log.warn(`Abuse detected for request${options.method}${options.url}`)}}})

Automatic retries

Many common request errors can be easily remediated by retrying the request. We recommend installing the@octokit/plugin-retry plugin for Automatic retries in these cases

constOctokit=require('@octokit/rest').plugin(require('@octokit/plugin-retry'))constoctokit=newOctokit()// all requests sent with the `octokit` instance are now retried up to 3 times for recoverable errors.

Logging

Octokit has 4 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 thelog client option. By default,octokit.log.debug() andoctokit.log.info() are no-ops, while the other two callconsole.warn() andconsole.error() respectively.

This is useful if you build reusableplugins.

Debug

The simplest way to receive debug information is to set thelog client option toconsole.

constoctokit=require('@octokit/rest')({log:console})console.request('/')

This will log

request { method: 'GET',  baseUrl: 'https://api.github.com',  headers:   { accept: 'application/vnd.github.v3+json',     'user-agent':      'octokit.js/0.0.0-semantically-released Node.js/10.15.0 (macOS Mojave; x64)' },  request: {},  url: '/' }GET / - 200 in 514ms

If you like to support a configurable log level, we recommend using theconsole-log-level module

constoctokit=require('@octokit/rest')({log:require('console-log-level')({level:'info'})})console.request('/')

This will only log

GET / - 200 in 514ms

Contributing

We would love you to contribute to@octokit/rest, pull requests are very welcomed! Please seeCONTRIBUTING.md for more information.

Credits

@octokit/rest was originally created asnode-githubin 2012 by Mike de Boer from Cloud9 IDE, Inc.It was adopted and renamed by GitHub in 2017

LICENSE

MIT

About

GitHub REST API client for JavaScript

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript91.9%
  • Smarty5.1%
  • TypeScript3.0%

[8]ページ先頭

©2009-2025 Movatter.jp