Convenience wrapper for Got to interact with the GitHub API

Overview

gh-got

Convenience wrapper for Got to interact with the GitHub API

Unless you're already using Got, you should probably use GitHub's own @octokit/rest.js or @octokit/graphql.js packages instead.

Install

$ npm install gh-got

Usage

Instead of:

const got = require('got');
const token = 'foo';

(async () => {
	const {body} = await got('https://api.github.com/users/sindresorhus', {
		json: true,
		headers: {
			'accept': 'application/vnd.github.v3+json',
			'authorization': `token ${token}`
		}
	});

	console.log(body.login);
	//=> 'sindresorhus'
})();

You can do:

const ghGot = require('gh-got');

(async () => {
	const {body} = await ghGot('users/sindresorhus', {token: 'foo'});

	console.log(body.login);
	//=> 'sindresorhus'
})();

Or:

const ghGot = require('gh-got');

(async () => {
	const {body} = await ghGot('https://api.github.com/users/sindresorhus', {token: 'foo'});

	console.log(body.login);
	//=> 'sindresorhus'
})();

API

Same API as got, including options, the stream API, aliases, pagination, etc, but with some additional options below.

Errors are improved by using the custom GitHub error messages. Doesn't apply to the stream API.

gh-got specific options

token

Type: string

GitHub access token.

Can be set globally with the GITHUB_TOKEN environment variable.

prefixUrl

Type: string
Default: https://api.github.com/

To support GitHub Enterprise.

Can be set globally with the GITHUB_ENDPOINT environment variable.

body

Type: object

Can be specified as a plain object and will be serialized as JSON with the appropriate headers set.

Rate limit

Responses and errors have a .rateLimit property with info about the current rate limit. (This is not yet implemented for the stream API)

const ghGot = require('gh-got');

(async () => {
	const {rateLimit} = await ghGot('users/sindresorhus');

	console.log(rateLimit);
	//=> {limit: 5000, remaining: 4899, reset: [Date 2018-12-31T20:45:20.000Z]}
})();

Authorization

Authorization for GitHub uses the following logic:

  1. If options.headers.authorization is passed to gh-got, then this will be used as first preference.
  2. If options.token is provided, then the authorization header will be set to token .
  3. If options.headers.authorization and options.token are not provided, then the authorization header will be set to token

In most cases, this means you can simply set GITHUB_TOKEN, but it also allows it to be overridden by setting options.token or options.headers.authorization explicitly. For example, if authenticating as a GitHub App, you could do the following:

const ghGot = require(`gh-got`);

(async () => {
	const options = {
		headers: {
			authorization: `Bearer ${jwt}`
		}
	};
	const {body} = await ghGot('app', options);

	console.log(body.name);
	//=> 'MyApp'
})();

Pagination

See the Got docs.

Comments
  • Pagination support?

    Pagination support?

    Issuehunt badges

    Would be nice to have pagination support in gh-got so consumers don't have to implement it themselves


    IssueHunt Summary

    szmarczak szmarczak has been rewarded.

    Backers (Total: $60.00)

    Submitted pull Requests


    Tips


    IssueHunt has been backed by the following sponsors. Become a sponsor

    enhancement help wanted :gift: Rewarded on Issuehunt 
    opened by steelbrain 14
  • Populate error with information from Github

    Populate error with information from Github

    The Github API returns error information in the body as encoded json, it would be nice to get better error messages by using this information.

    e.g.

    HTTP/1.1 400 Bad Request
    Content-Length: 35
    
    {"message":"Problems parsing JSON"}
    

    currently results in:

    HTTPError: Response code 400 (Bad Request)
    

    would be nice to get something like:

    GithubError: Problems parsing JSON (400)
    
    enhancement help wanted 
    opened by LinusU 7
  • silent or mute option?

    silent or mute option?

    this passing noop function to got is weird and okey I understand why is it, but break some things sometimes. I think better would be to have silent or mute option and pass it if you dont want to catch the things.

    opened by tunnckoCore 7
  • Stringify body as JSON by default

    Stringify body as JSON by default

    I wanted to add a test but I'm not sure exactly what direction to take since POST requests usually modify remote state. My current ideas are

    • Edit a gist that we create specifically for this
    • Post a reaction to a specific comment
    • Start an HTTP server, set endpoint to localhost:randomport and verify that body is JSON
    • Use nock or similar to capture the outgoing request

    Actually, maybe we want to use Nock in all the tests since it won't require an active connection and token to Github, thoughts?

    Fixes #20.

    opened by LinusU 6
  • Support `options.endpoint` without trailing slash

    Support `options.endpoint` without trailing slash

    Any endpoint passed via options without trailing slash was failing, because trailing slash was only massaged when passed via env. Refactored to use url.resolve instead of manual replace.

    Also, running npm test on master was broken until I added one object destructuring.

    opened by rarkins 4
  • Is creating gists supported?

    Is creating gists supported?

    Tried via

    await ghGot(apiUrl, { token: this._token, method: 'post' })
    

    as well as

    await ghGot.post(apiUrl, { token: this._token })
    

    but i get a (node:30976) UnhandledPromiseRejectionWarning: HTTPError: Response code 404 (Not Found)

    I wonder if i'm being clumsy or that gh-got does not support this part of the api?

    opened by kvz 4
  • GHE envvar overrides normal usage

    GHE envvar overrides normal usage

    I occasionally use gh-got as a dep for both github.com and GHE apis. I have an env var, GITHUB_ENDPOINT, for the latter. However, this code:

    endpoint: env.GITHUB_ENDPOINT ? env.GITHUB_ENDPOINT.replace(/[^/]$/, '$&/') : 'https://api.github.com/'
    

    Assumes that I am always using it. This breaks some use cases. I could look up and install directory based environment managers, but I am wondering if an easier fix would be to ensure that this setting is only called when you send an opt in. Right now, there isn't even an option for that.

    How would you deal with this?

    opened by RichardLitt 4
  • Use error message returned from GitHub

    Use error message returned from GitHub

    As discussed in #19, I skipped formatting the errors in the streaming API. Not sure how you want it documented though so any input on that would be helpful.

    Also, feels like the tests fails because of some globals leaking out from the serial tests. Have something changed in ava regarding the order in which the tests are ran.


    Fixes #19

    opened by kevva 4
  • Reversing priority of token and endpoint environment variables

    Reversing priority of token and endpoint environment variables

    Started as a line comment but let's make it an issue and fix/close it.

    The readme says clearly:

    Can be overridden globally with the GITHUB_TOKEN environment variable.

    Same for the endpoint.

    Not sure what the logic was, but I think it would be preferable to use the environment variables only when no applicable argument is passed. An application could have a default token (the env.) but for whatever reason use another token on specific calls.

    The module, readme and test would have to be updated. It could be considered a major change since it's reversing its meaning.

    opened by millette 4
  • Update to Got 10

    Update to Got 10

    opened by szmarczak 2
  • Don't override `authorization` header if it already exists

    Don't override `authorization` header if it already exists

    Only use options.token to set options.headers.authorization if that header is current unset.

    This covers the case where:

    1. User has a GITHUB_TOKEN defined in env
    2. User/app has explicitly set an authorization header and is definitely not expecting it to get ignored/overwritten

    This is particularly important also for GitHub "Apps" which need to authentication themselves via Bearer not token, so it's impossible to pass that in options.token either.

    opened by rarkins 2
Releases(v10.0.0)
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Isomorphic WHATWG Fetch API, for Node & Browserify

isomorphic-fetch Fetch for node and Browserify. Built on top of GitHub's WHATWG Fetch polyfill. Warnings This adds fetch as a global so that its API i

Matt Andrews 6.9k Jan 2, 2023
A light-weight module that brings the Fetch API to Node.js

A light-weight module that brings Fetch API to Node.js. Consider supporting us on our Open Collective: Motivation Features Difference from client-side

Node Fetch 8.1k Jan 4, 2023
Bearer provides all of the tools to build, run and manage API integrations.

Bearer - The API Integration Framework Bearer provides all of the tools to build, run and manage API Learn more Archive Status Bearer JS has been arch

Bearer.sh 22 Oct 31, 2022
An HTTP Web Server for Chrome (chrome.sockets API)

An HTTP Web Server for Chrome (chrome.sockets API)

Kyle Graehl 1.2k Dec 31, 2022
Get a full fake REST API with zero coding in less than 30 seconds (seriously)

JSON Server Get a full fake REST API with zero coding in less than 30 seconds (seriously) Created with <3 for front-end developers who need a quick ba

null 64.9k Jan 3, 2023
Prefect API Authentication/Authorization Proxy for on-premises deployments

Proxy Authorization Service for Prefect UI and Prefect CLI Prefect is a great platform for building data flows/pipelines. It supports hybrid execution

Softrams 20 Dec 10, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity

Wren Wren is a small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity. convenient aliases for HTTP responses au

Jakub Neander 69 Dec 12, 2022
Node JS/TypeScript module that allows you to work with the site enka.network adding localization and convenience.

enkaNetwork Node JS/TypeScript module that allows you to work with the site enka.network adding localization and convenience. examples • structure ??

kravets 12 Nov 18, 2022
The Cassandra/Scylla library you didn't want but got anyways.

Installation Using npm: npm install scyllo or if you prefer to use the yarn package manager: yarn add scyllo Usage import { ScylloClient } from 'scyll

LVK.SH 7 Jul 20, 2022
My terrible attempt at a promposal. Update: She said yes LMFAO Update Update: I got friendzoned right after 😭

TypeScript Next.js example This is a really simple project that shows the usage of Next.js with TypeScript. Deploy your own Deploy the example using V

John Li (Tet) 7 Oct 27, 2022
Remix enables you to build fantastic user experiences for the web and feel happy with the code that got you there. In this workshop, we'll look at some more advanced use cases when building Remix applications.

?? Advanced Remix Workshop Remix enables you to build fantastic user experiences for the web and feel happy with the code that got you there. In this

Frontend Masters 167 Dec 9, 2022
Remix enables you to build fantastic user experiences for the web and feel happy with the code that got you there. Get a jumpstart on Remix with this workshop.

?? Remix Fundamentals Build Better websites with Remix Remix enables you to build fantastic user experiences for the web and feel happy with the code

Frontend Masters 204 Dec 25, 2022
Veselin Petranchev 2 Oct 11, 2022
Lightweight WebSocketServer wrapper lib using ws-wrapper to wrap connected WebSockets

ws-server-wrapper Lightweight WebSocketServer wrapper lib using ws-wrapper and ws to wrap connected WebSockets. The only dependency is ws-wrapper itse

Blake Miner 17 May 9, 2022
discord.js is a powerful Node.js module that allows you to easily interact with the Discord API.

A powerful JavaScript library for interacting with the Discord API

Discord.js 21.6k Jan 5, 2023
A URL Shortener That Allow Users To Interact With Its API Through A Discord Bot

Shortem A URL Shortener That Allow Users To Interact With Its API Through A Discord Bot About Supports Multiple Databases Performant Uses discord.js v

Bots Studios 19 Sep 1, 2022