• Stars
    star
    13,762
  • Rank 2,232 (Top 0.05 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌳 Tiny & elegant JavaScript HTTP client based on the Fetch API

ky


Sindre's open source work is supported by the community.
Special thanks to:


SerpApi
API to get search engine results with ease.
SerpApi
API to get search engine results with ease.









Ky is a tiny and elegant HTTP client based on the browser Fetch API

Coverage Status

Ky targets modern browsers and Deno. For older browsers, you will need to transpile and use a fetch polyfill and globalThis polyfill. For isomorphic needs (Node.js + browser, like SSR), check out ky-universal.

It's just a tiny file with no dependencies.

Benefits over plain fetch

  • Simpler API
  • Method shortcuts (ky.post())
  • Treats non-2xx status codes as errors (after redirects)
  • Retries failed requests
  • JSON option
  • Timeout support
  • URL prefix option
  • Instances with custom defaults
  • Hooks

Install

npm install ky
Download
CDN

Usage

import ky from 'ky';

const json = await ky.post('https://example.com', {json: {foo: true}}).json();

console.log(json);
//=> `{data: '🦄'}`

With plain fetch, it would be:

class HTTPError extends Error {}

const response = await fetch('https://example.com', {
	method: 'POST',
	body: JSON.stringify({foo: true}),
	headers: {
		'content-type': 'application/json'
	}
});

if (!response.ok) {
	throw new HTTPError(`Fetch error: ${response.statusText}`);
}

const json = await response.json();

console.log(json);
//=> `{data: '🦄'}`

If you are using Deno, import Ky from a URL. For example, using a CDN:

import ky from 'https://esm.sh/ky';

API

ky(input, options?)

The input and options are the same as fetch, with some exceptions:

  • The credentials option is same-origin by default, which is the default in the spec too, but not all browsers have caught up yet.
  • Adds some more options. See below.

Returns a Response object with Body methods added for convenience. So you can, for example, call ky.get(input).json() directly without having to await the Response first. When called like that, an appropriate Accept header will be set depending on the body method used. Unlike the Body methods of window.Fetch; these will throw an HTTPError if the response status is not in the range of 200...299. Also, .json() will return an empty string if body is empty or the response status is 204 instead of throwing a parse error due to an empty body.

ky.get(input, options?)

ky.post(input, options?)

ky.put(input, options?)

ky.patch(input, options?)

ky.head(input, options?)

ky.delete(input, options?)

Sets options.method to the method name and makes a request.

When using a Request instance as input, any URL altering options (such as prefixUrl) will be ignored.

options

Type: object

method

Type: string
Default: 'get'

HTTP method used to make the request.

Internally, the standard methods (GET, POST, PUT, PATCH, HEAD and DELETE) are uppercased in order to avoid server errors due to case sensitivity.

json

Type: object and any other value accepted by JSON.stringify()

Shortcut for sending JSON. Use this instead of the body option. Accepts any plain object or value, which will be JSON.stringify()'d and sent in the body with the correct header set.

searchParams

Type: string | object<string, string | number | boolean> | Array<Array<string | number | boolean>> | URLSearchParams
Default: ''

Search parameters to include in the request URL. Setting this will override all existing search parameters in the input URL.

Accepts any value supported by URLSearchParams().

prefixUrl

Type: string | URL

A prefix to prepend to the input URL when making the request. It can be any valid URL, either relative or absolute. A trailing slash / is optional and will be added automatically, if needed, when it is joined with input. Only takes effect when input is a string. The input argument cannot start with a slash / when using this option.

Useful when used with ky.extend() to create niche-specific Ky-instances.

import ky from 'ky';

// On https://example.com

const response = await ky('unicorn', {prefixUrl: '/api'});
//=> 'https://example.com/api/unicorn'

const response2 = await ky('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'

Notes:

  • After prefixUrl and input are joined, the result is resolved against the base URL of the page (if any).
  • Leading slashes in input are disallowed when using this option to enforce consistency and avoid confusion about how the input URL is handled, given that input will not follow the normal URL resolution rules when prefixUrl is being used, which changes the meaning of a leading slash.
retry

Type: object | number
Default:

  • limit: 2
  • methods: get put head delete options trace
  • statusCodes: 408 413 429 500 502 503 504
  • maxRetryAfter: undefined
  • backoffLimit: undefined

An object representing limit, methods, statusCodes and maxRetryAfter fields for maximum retry count, allowed methods, allowed status codes and maximum Retry-After time.

If retry is a number, it will be used as limit and other defaults will remain in place.

If maxRetryAfter is set to undefined, it will use options.timeout. If Retry-After header is greater than maxRetryAfter, it will cancel the request.

The backoffLimit option is the upper limit of the delay per retry in milliseconds. To clamp the delay, set backoffLimit to 1000, for example. By default, the delay is calculated with 0.3 * (2 ** (attemptCount - 1)) * 1000. The delay increases exponentially.

Retries are not triggered following a timeout.

import ky from 'ky';

const json = await ky('https://example.com', {
	retry: {
		limit: 10,
		methods: ['get'],
		statusCodes: [413],
		backoffLimit: 3000
	}
}).json();
timeout

Type: number | false
Default: 10000

Timeout in milliseconds for getting a response, including any retries. Can not be greater than 2147483647. If set to false, there will be no timeout.

hooks

Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}

Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.

hooks.beforeRequest

Type: Function[]
Default: []

This hook enables you to modify the request right before it is sent. Ky will make no further changes to the request after this. The hook function receives request and options as arguments. You could, for example, modify the request.headers here.

The hook can return a Request to replace the outgoing request, or return a Response to completely avoid making an HTTP request. This can be used to mock a request, check an internal cache, etc. An important consideration when returning a request or response from this hook is that any remaining beforeRequest hooks will be skipped, so you may want to only return them from the last hook.

import ky from 'ky';

const api = ky.extend({
	hooks: {
		beforeRequest: [
			request => {
				request.headers.set('X-Requested-With', 'ky');
			}
		]
	}
});

const response = await api.get('https://example.com/api/users');
hooks.beforeRetry

Type: Function[]
Default: []

This hook enables you to modify the request right before retry. Ky will make no further changes to the request after this. The hook function receives an object with the normalized request and options, an error instance, and the retry count. You could, for example, modify request.headers here.

If the request received a response, the error will be of type HTTPError and the Response object will be available at error.response. Be aware that some types of errors, such as network errors, inherently mean that a response was not received. In that case, the error will not be an instance of HTTPError.

You can prevent Ky from retrying the request by throwing an error. Ky will not handle it in any way and the error will be propagated to the request initiator. The rest of the beforeRetry hooks will not be called in this case. Alternatively, you can return the ky.stop symbol to do the same thing but without propagating an error (this has some limitations, see ky.stop docs for details).

import ky from 'ky';

const response = await ky('https://example.com', {
	hooks: {
		beforeRetry: [
			async ({request, options, error, retryCount}) => {
				const token = await ky('https://example.com/refresh-token');
				request.headers.set('Authorization', `token ${token}`);
			}
		]
	}
});
hooks.beforeError

Type: Function[]
Default: []

This hook enables you to modify the HTTPError right before it is thrown. The hook function receives a HTTPError as an argument and should return an instance of HTTPError.

import ky from 'ky';

await ky('https://example.com', {
	hooks: {
		beforeError: [
			error => {
				const {response} = error;
				if (response && response.body) {
					error.name = 'GitHubError';
					error.message = `${response.body.message} (${response.status})`;
				}

				return error;
			}
		]
	}
});
hooks.afterResponse

Type: Function[]
Default: []

This hook enables you to read and optionally modify the response. The hook function receives normalized request, options, and a clone of the response as arguments. The return value of the hook function will be used by Ky as the response object if it's an instance of Response.

import ky from 'ky';

const response = await ky('https://example.com', {
	hooks: {
		afterResponse: [
			(_request, _options, response) => {
				// You could do something with the response, for example, logging.
				log(response);

				// Or return a `Response` instance to overwrite the response.
				return new Response('A different response', {status: 200});
			},

			// Or retry with a fresh token on a 403 error
			async (request, options, response) => {
				if (response.status === 403) {
					// Get a fresh token
					const token = await ky('https://example.com/token').text();

					// Retry with the token
					request.headers.set('Authorization', `token ${token}`);

					return ky(request);
				}
			}
		]
	}
});
throwHttpErrors

Type: boolean
Default: true

Throw an HTTPError when, after following redirects, the response has a non-2xx status code. To also throw for redirects instead of following them, set the redirect option to 'manual'.

Setting this to false may be useful if you are checking for resource availability and are expecting error responses.

Note: If false, error responses are considered successful and the request will not be retried.

onDownloadProgress

Type: Function

Download progress event handler.

The function receives a progress and chunk argument:

  • The progress object contains the following elements: percent, transferredBytes and totalBytes. If it's not possible to retrieve the body size, totalBytes will be 0.
  • The chunk argument is an instance of Uint8Array. It's empty for the first call.
import ky from 'ky';

const response = await ky('https://example.com', {
	onDownloadProgress: (progress, chunk) => {
		// Example output:
		// `0% - 0 of 1271 bytes`
		// `100% - 1271 of 1271 bytes`
		console.log(`${progress.percent * 100}% - ${progress.transferredBytes} of ${progress.totalBytes} bytes`);
	}
});
parseJson

Type: Function
Default: JSON.parse()

User-defined JSON-parsing function.

Use-cases:

  1. Parse JSON via the bourne package to protect from prototype pollution.
  2. Parse JSON with reviver option of JSON.parse().
import ky from 'ky';
import bourne from '@hapijs/bourne';

const json = await ky('https://example.com', {
	parseJson: text => bourne(text)
}).json();
fetch

Type: Function
Default: fetch

User-defined fetch function. Has to be fully compatible with the Fetch API standard.

Use-cases:

  1. Use custom fetch implementations like isomorphic-unfetch.
  2. Use the fetch wrapper function provided by some frameworks that use server-side rendering (SSR).
import ky from 'ky';
import fetch from 'isomorphic-unfetch';

const json = await ky('https://example.com', {fetch}).json();

ky.extend(defaultOptions)

Create a new ky instance with some defaults overridden with your own.

In contrast to ky.create(), ky.extend() inherits defaults from its parent.

You can pass headers as a Headers instance or a plain object.

You can remove a header with .extend() by passing the header with an undefined value. Passing undefined as a string removes the header only if it comes from a Headers instance.

import ky from 'ky';

const url = 'https://sindresorhus.com';

const original = ky.create({
	headers: {
		rainbow: 'rainbow',
		unicorn: 'unicorn'
	}
});

const extended = original.extend({
	headers: {
		rainbow: undefined
	}
});

const response = await extended(url).json();

console.log('rainbow' in response);
//=> false

console.log('unicorn' in response);
//=> true

ky.create(defaultOptions)

Create a new Ky instance with complete new defaults.

import ky from 'ky';

// On https://my-site.com

const api = ky.create({prefixUrl: 'https://example.com/api'});

const response = await api.get('users/123');
//=> 'https://example.com/api/users/123'

const response = await api.get('/status', {prefixUrl: ''});
//=> 'https://my-site.com/status'

defaultOptions

Type: object

ky.stop

A Symbol that can be returned by a beforeRetry hook to stop the retry. This will also short circuit the remaining beforeRetry hooks.

Note: Returning this symbol makes Ky abort and return with an undefined response. Be sure to check for a response before accessing any properties on it or use optional chaining. It is also incompatible with body methods, such as .json() or .text(), because there is no response to parse. In general, we recommend throwing an error instead of returning this symbol, as that will cause Ky to abort and then throw, which avoids these limitations.

A valid use-case for ky.stop is to prevent retries when making requests for side effects, where the returned data is not important. For example, logging client activity to the server.

import ky from 'ky';

const options = {
	hooks: {
		beforeRetry: [
			async ({request, options, error, retryCount}) => {
				const shouldStopRetry = await ky('https://example.com/api');
				if (shouldStopRetry) {
					return ky.stop;
				}
			}
		]
	}
};

// Note that response will be `undefined` in case `ky.stop` is returned.
const response = await ky.post('https://example.com', options);

// Using `.text()` or other body methods is not supported.
const text = await ky('https://example.com', options).text();

HTTPError

Exposed for instanceof checks. The error has a response property with the Response object, request property with the Request object, and options property with normalized options (either passed to ky when creating an instance with ky.create() or directly when performing the request).

If you need to read the actual response when an HTTPError has occurred, call the respective parser method on the response object. For example:

try {
	await ky('https://example.com').json();
} catch (error) {
	if (error.name === 'HTTPError') {
		const errorJson = await error.response.json();
	}
}

TimeoutError

The error thrown when the request times out. It has a request property with the Request object.

Tips

Sending form data

Sending form data in Ky is identical to fetch. Just pass a FormData instance to the body option. The Content-Type header will be automatically set to multipart/form-data.

import ky from 'ky';

// `multipart/form-data`
const formData = new FormData();
formData.append('food', 'fries');
formData.append('drink', 'icetea');

const response = await ky.post(url, {body: formData});

If you want to send the data in application/x-www-form-urlencoded format, you will need to encode the data with URLSearchParams.

import ky from 'ky';

// `application/x-www-form-urlencoded`
const searchParams = new URLSearchParams();
searchParams.set('food', 'fries');
searchParams.set('drink', 'icetea');

const response = await ky.post(url, {body: searchParams});

Setting a custom Content-Type

Ky automatically sets an appropriate Content-Type header for each request based on the data in the request body. However, some APIs require custom, non-standard content types, such as application/x-amz-json-1.1. Using the headers option, you can manually override the content type.

import ky from 'ky';

const json = await ky.post('https://example.com', {
	headers: {
		'content-type': 'application/json'
	},
	json: {
		foo: true
	},
}).json();

console.log(json);
//=> `{data: '🦄'}`

Cancellation

Fetch (and hence Ky) has built-in support for request cancellation through the AbortController API. Read more.

Example:

import ky from 'ky';

const controller = new AbortController();
const {signal} = controller;

setTimeout(() => {
	controller.abort();
}, 5000);

try {
	console.log(await ky(url, {signal}).text());
} catch (error) {
	if (error.name === 'AbortError') {
		console.log('Fetch aborted');
	} else {
		console.error('Fetch error:', error);
	}
}

FAQ

How do I use this in Node.js?

Check out ky-universal.

How do I use this with a web app (React, Vue.js, etc.) that uses server-side rendering (SSR)?

Check out ky-universal.

How do I test a browser library that uses this?

Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal. Read more.

How do I use this without a bundler like Webpack?

Make sure your code is running as a JavaScript module (ESM), for example by using a <script type="module"> tag in your HTML document. Then Ky can be imported directly by that module without a bundler or other tools.

<script type="module">
import ky from 'https://unpkg.com/ky/distribution/index.js';

const json = await ky('https://jsonplaceholder.typicode.com/todos/1').json();

console.log(json.title);
//=> 'delectus aut autem
</script>

How is it different from got

See my answer here. Got is maintained by the same people as Ky.

How is it different from axios?

See my answer here.

How is it different from r2?

See my answer in #10.

What does ky mean?

It's just a random short npm package name I managed to get. It does, however, have a meaning in Japanese:

A form of text-able slang, KY is an abbreviation for 空気読めない (kuuki yomenai), which literally translates into “cannot read the air.” It's a phrase applied to someone who misses the implied meaning.

Browser support

The latest version of Chrome, Firefox, and Safari.

Node.js support

Polyfill the needed browser globals or just use ky-universal.

Related

  • ky-universal - Use Ky in both Node.js and browsers
  • got - Simplified HTTP requests for Node.js
  • ky-hooks-change-case - Ky hooks to modify cases on requests and responses of objects

Maintainers

More Repositories

1

awesome

😎 Awesome lists about all kinds of interesting topics
270,042
star
2

awesome-nodejs

⚡ Delightful Node.js packages and resources
52,854
star
3

awesome-electron

Useful resources for creating apps with Electron
25,634
star
4

quick-look-plugins

List of useful Quick Look plugins for developers
17,497
star
5

got

🌐 Human-friendly and powerful HTTP request library for Node.js
TypeScript
14,218
star
6

type-fest

A collection of essential TypeScript types
TypeScript
14,015
star
7

pure

Pretty, minimal and fast ZSH prompt
Shell
12,391
star
8

pageres

Capture website screenshots
TypeScript
9,573
star
9

ora

Elegant terminal spinner
JavaScript
8,591
star
10

np

A better `npm publish`
JavaScript
7,529
star
11

github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
CSS
7,421
star
12

caprine

Elegant Facebook Messenger desktop app
TypeScript
7,014
star
13

screenfull

Simple wrapper for cross-browser usage of the JavaScript Fullscreen API
HTML
6,891
star
14

Gifski

🌈 Convert videos to high-quality GIFs on your Mac
Swift
6,807
star
15

fkill-cli

Fabulously kill processes. Cross-platform.
JavaScript
6,782
star
16

query-string

Parse and stringify URL query strings
JavaScript
6,453
star
17

execa

Process execution for humans
JavaScript
6,019
star
18

modern-normalize

🐒 Normalize browsers' default style
TypeScript
5,038
star
19

css-in-readme-like-wat

Style your readme using CSS with this simple trick
5,013
star
20

awesome-npm

Awesome npm resources and tips
4,315
star
21

promise-fun

Promise packages, patterns, chat, and tutorials
4,277
star
22

awesome-scifi

Sci-Fi worth consuming
4,268
star
23

electron-store

Simple data persistence for your Electron app or module - Save and load user preferences, app state, cache, etc
JavaScript
4,165
star
24

create-dmg

Create a good-looking DMG for your macOS app in seconds
JavaScript
3,950
star
25

speed-test

Test your internet connection speed and ping using speedtest.net from the CLI
JavaScript
3,882
star
26

eslint-plugin-unicorn

More than 100 powerful ESLint rules
JavaScript
3,877
star
27

ow

Function argument validation for humans
TypeScript
3,799
star
28

file-type

Detect the file type of a file, stream, or data
JavaScript
3,632
star
29

meow

🐈 CLI app helper
JavaScript
3,305
star
30

p-queue

Promise queue with concurrency control
TypeScript
3,202
star
31

open

Open stuff like URLs, files, executables. Cross-platform.
JavaScript
2,976
star
32

Plash

💦 Make any website your Mac desktop wallpaper
Swift
2,735
star
33

alfy

Create Alfred workflows with ease
JavaScript
2,570
star
34

trash

Move files and directories to the trash
JavaScript
2,512
star
35

fast-cli

Test your download and upload speed using fast.com
JavaScript
2,484
star
36

guides

A collection of succinct guides - Public Domain
2,424
star
37

globby

User-friendly glob matching
JavaScript
2,376
star
38

slugify

Slugify a string
JavaScript
2,357
star
39

emoj

Find relevant emoji from text on the command-line 😮 ✨ 🙌 🐴 💥 🙈
JavaScript
2,311
star
40

cli-spinners

Spinners for use in the terminal
JavaScript
2,255
star
41

on-change

Watch an object or array for changes
JavaScript
1,966
star
42

devtools-detect

Detect if DevTools is open and its orientation
HTML
1,924
star
43

gulp-imagemin

Minify PNG, JPEG, GIF and SVG images
JavaScript
1,903
star
44

touch-bar-simulator

Use the Touch Bar on any Mac
Swift
1,900
star
45

notifier-for-github

Browser extension - Get notified about new GitHub notifications
JavaScript
1,828
star
46

editorconfig-sublime

Sublime Text plugin for EditorConfig - Helps developers maintain consistent coding styles between different editors
Python
1,757
star
47

emittery

Simple and modern async event emitter
JavaScript
1,721
star
48

is

Type check values
TypeScript
1,678
star
49

capture-website

Capture screenshots of websites
JavaScript
1,670
star
50

Defaults

💾 Swifty and modern UserDefaults
Swift
1,661
star
51

electron-boilerplate

Boilerplate to kickstart creating an app with Electron
JavaScript
1,632
star
52

pageres-cli

Capture website screenshots
JavaScript
1,620
star
53

clipboardy

Access the system clipboard (copy/paste)
JavaScript
1,598
star
54

gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` → `unicorn-d41d8cd98f.css`
JavaScript
1,538
star
55

pify

Promisify a callback-style function
JavaScript
1,494
star
56

boxen

Create boxes in the terminal
JavaScript
1,467
star
57

Actions

⚙️ Supercharge your shortcuts
Swift
1,437
star
58

multiline

Multiline strings in JavaScript
JavaScript
1,424
star
59

hyper-snazzy

Elegant Hyper theme with bright colors
JavaScript
1,412
star
60

amas

Awesome & Marvelous Amas
1,392
star
61

LaunchAtLogin

Add “Launch at Login” functionality to your macOS app in seconds
Swift
1,346
star
62

del

Delete files and directories
JavaScript
1,316
star
63

refined-twitter

Browser extension that simplifies the Twitter interface and adds useful features
JavaScript
1,313
star
64

KeyboardShortcuts

⌨️ Add user-customizable global keyboard shortcuts (hotkeys) to your macOS app in minutes
Swift
1,313
star
65

iterm2-snazzy

Elegant iTerm2 theme with bright colors
1,313
star
66

electron-context-menu

Context menu for your Electron app
JavaScript
1,297
star
67

p-limit

Run multiple promise-returning & async functions with limited concurrency
JavaScript
1,294
star
68

Settings

⚙ Add a settings window to your macOS app in minutes
Swift
1,282
star
69

trash-cli

Move files and folders to the trash
JavaScript
1,244
star
70

electron-util

Useful utilities for Electron apps and modules
JavaScript
1,188
star
71

is-online

Check if the internet connection is up
JavaScript
1,181
star
72

ponyfill

🦄 Like polyfill but with pony pureness
1,136
star
73

conf

Simple config handling for your app or module
TypeScript
1,109
star
74

anatine

[DEPRECATED] 🐦 Pristine Twitter app
JavaScript
1,097
star
75

electron-dl

Simplified file downloads for your Electron app
JavaScript
1,087
star
76

log-update

Log by overwriting the previous output in the terminal. Useful for rendering progress bars, animations, etc.
JavaScript
1,027
star
77

pretty-bytes

Convert bytes to a human readable string: 1337 → 1.34 kB
JavaScript
1,022
star
78

grunt-sass

Compile Sass to CSS
JavaScript
1,020
star
79

mem

Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
TypeScript
1,019
star
80

DockProgress

Show progress in your app's Dock icon
Swift
1,003
star
81

wallpaper

Manage the desktop wallpaper
JavaScript
996
star
82

p-map

Map over promises concurrently
JavaScript
996
star
83

public-ip

Get your public IP address - very fast!
JavaScript
979
star
84

gulp-app

[DEPRECATED] Gulp as an app
JavaScript
961
star
85

grunt-shell

Run shell commands
JavaScript
952
star
86

load-grunt-tasks

Load multiple grunt tasks using globbing patterns
JavaScript
940
star
87

hasha

Hashing made simple. Get the hash of a buffer/string/stream/file.
JavaScript
934
star
88

pretty-ms

Convert milliseconds to a human readable string: `1337000000` → `15d 11h 23m 20s`
JavaScript
929
star
89

terminal-image

Display images in the terminal
JavaScript
923
star
90

object-assign

ES2015 Object.assign() ponyfill
JavaScript
922
star
91

copy-text-to-clipboard

Copy text to the clipboard in modern browsers (0.2 kB)
JavaScript
858
star
92

System-Color-Picker

🎨 The macOS color picker as an app with more features
Swift
842
star
93

normalize-url

Normalize a URL
JavaScript
818
star
94

get-port

Get an available TCP port
JavaScript
817
star
95

atom-editorconfig

Helps developers maintain consistent coding styles between different editors
JavaScript
811
star
96

grunt-concurrent

Run grunt tasks concurrently
JavaScript
799
star
97

dot-prop

Get, set, or delete a property from a nested object using a dot path
JavaScript
777
star
98

p-progress

Create a promise that reports progress
TypeScript
751
star
99

gulp-changed

Only pass through changed files
JavaScript
747
star
100

generator-nm

Scaffold out a node module
JavaScript
742
star