Coder Social home page Coder Social logo

ky's Introduction


ky



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

Build Status codecov

Ky targets modern browsers. For older browsers, you will need to transpile and use a fetch polyfill. For Node.js, check out Got.

1 KB (minified & gzipped), one file, and no dependencies.

Benefits over plain fetch

  • Simpler API
  • Method shortcuts (ky.post())
  • Treats non-200 status codes as errors
  • Retries failed requests
  • JSON option
  • Timeout support
  • Instances with custom defaults

Install

$ npm install ky

Usage

import ky from 'ky';

(async () => {
	const json = await ky.post('https://some-api.com', {json: {foo: true}}).json();

	console.log(json);
	//=> `{data: '๐Ÿฆ„'}`
})();

With plain fetch, it would be:

(async () => {
	class HTTPError extends Error {}

	const response = await fetch('https://sindresorhus.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: '๐Ÿฆ„'}`
})();

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.json() directly on the Response without having to await it first. Unlike the Body methods of window.Fetch; these will throw an HTTPError if the response status is not in the range 200...299.

options

Type: Object

json

Type: Object

Shortcut for sending JSON. Use this instead of the body option. Accepts a plain object which will be JSON.stringify()'d and the correct header will be set for you.

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.

retry

Type: number
Default: 2

Retry failed requests made with one of the below methods that result in a network error or one of the below status codes.

Methods: GET PUT HEAD DELETE OPTIONS TRACE
Status codes: 408 413 429 500 502 503 504

timeout

Type: number
Default: 10000

Timeout in milliseconds for getting a response.

ky.extend(defaultOptions)

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

defaultOptions

Type: Object

ky.HTTPError

Exposed for instanceof checks. The error has a response property with the Response object.

ky.TimeoutError

The error thrown when the request times out.

Tips

Cancelation

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

Example:

import ky from 'ky';

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

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

(async () => {
	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 is it different from r2?

See my answer in #10.

Browser support

The latest version of Chrome, Firefox, and Safari.

Related

  • got - Simplified HTTP requests for Node.js

License

MIT ยฉ Sindre Sorhus

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.