What is ky?
The ky npm package is a tiny and elegant HTTP client based on the browser's Fetch API. It provides a simpler and more powerful interface for making HTTP requests and handling responses. It is designed to be used with modern JavaScript, including support for async/await syntax.
What are ky's main functionalities?
GET requests
This feature allows you to perform GET requests to retrieve data from a specified resource. The example code demonstrates how to make a GET request and parse the response as JSON.
const json = await ky.get('https://jsonplaceholder.typicode.com/todos/1').json();
POST requests
This feature enables you to send POST requests to submit data to a server. The example code shows how to make a POST request with a JSON body and parse the response as JSON.
const json = await ky.post('https://jsonplaceholder.typicode.com/posts', { json: { title: 'foo', body: 'bar', userId: 1 } }).json();
Error handling
Ky provides simple error handling for failed HTTP requests. The example code demonstrates how to catch errors when a request fails, such as when the URL is invalid.
ky.get('https://jsonplaceholder.typicode.com/invalid-url').then(response => console.log(response)).catch(error => console.error(error));
Timeouts
Ky allows you to specify a timeout for the request. If the request takes longer than the specified time, it will be aborted. The example code sets a timeout of 5000 milliseconds.
ky.get('https://jsonplaceholder.typicode.com/todos', { timeout: 5000 }).then(response => console.log(response));
Hooks
Ky provides hooks that allow you to intercept requests and responses to perform actions or modify them. The example code logs a message before the request is made.
ky.get('https://jsonplaceholder.typicode.com/todos', { hooks: { beforeRequest: [request => { console.log('About to make a request', request); }] } }).then(response => console.log(response));
Other packages similar to ky
axios
Axios is a popular HTTP client for the browser and node.js. It supports promise-based API, interceptors, request cancellation, and more. Compared to ky, axios works in both the browser and Node.js environments, while ky is designed primarily for modern browsers.
got
Got is a powerful HTTP client for Node.js. It provides a lot of features like streams, retries, and advanced error handling. Unlike ky, which is built on the Fetch API, got is more suitable for server-side use and offers a wider range of options for Node.js developers.
node-fetch
node-fetch is a light-weight module that brings the browser's Fetch API to Node.js. It aims to provide a consistent API with the browser's Fetch, making it a closer alternative to ky for server-side development. However, ky offers additional features and a more fluent API on top of the basic Fetch functionality.
superagent
Superagent is a small progressive client-side HTTP request library. It has a flexible and expressive API that allows for chaining methods. Superagent is similar to ky in terms of client-side usage but does not rely on the Fetch API and has a different API design.
Ky is a tiny and elegant HTTP client based on the browser Fetch API
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);
})();
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);
})();
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.
Browser support
The latest version of Chrome, Firefox, and Safari.
Related
- got - Simplified HTTP requests for Node.js
License
MIT © Sindre Sorhus