Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
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.
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));
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 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 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 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 and Deno. For older browsers, you will need to transpile and use a fetch
polyfill. For Node.js, check out Got. For isomorphic needs (like SSR), check out ky-universal
.
It's just a tiny file with no dependencies.
fetch
ky.post()
)$ npm install ky
import ky from 'ky';
(async () => {
const parsed = await ky.post('https://example.com', {json: {foo: true}}).json();
console.log(parsed);
//=> `{data: '🦄'}`
})();
With plain fetch
, it would be:
(async () => {
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 parsed = await response.json();
console.log(parsed);
//=> `{data: '🦄'}`
})();
If you are using Deno, import Ky from a URL. For example, using a CDN:
import ky from 'https://unpkg.com/ky/index.js';
In environments that do not support import
, you can load ky
in UMD format. For example, using require()
:
const ky = require('ky/umd');
With the UMD version, it's also easy to use ky
without a bundler or module system.
The input
and options
are the same as fetch
, with some exceptions:
credentials
option is same-origin
by default, which is the default in the spec too, but not all browsers have caught up yet.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 the response status is 204
instead of throwing a parse error due to an empty body.
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.
Type: object
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.
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.
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()
.
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
(async () => {
await ky('unicorn', {prefixUrl: '/api'});
//=> 'https://example.com/api/unicorn'
await ky('unicorn', {prefixUrl: 'https://cats.com'});
//=> 'https://cats.com/unicorn'
})();
Notes:
prefixUrl
and input
are joined, the result is resolved against the base URL of the page (if any).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.Type: object | number
Default:
limit
: 2
methods
: get
put
head
delete
options
trace
statusCodes
: 408
413
429
500
502
503
504
maxRetryAfter
: 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.
Delays between retries is calculated with the function 0.3 * (2 ** (retry - 1)) * 1000
, where retry
is the attempt number (starts from 1).
import ky from 'ky';
(async () => {
const parsed = await ky('https://example.com', {
retry: {
limit: 10,
methods: ['get'],
statusCodes: [413]
}
}).json();
})();
Type: number | false
Default: 10000
Timeout in milliseconds for getting a response. Can not be greater than 2147483647.
If set to false
, there will be no timeout.
Type: object<string, Function[]>
Default: {beforeRequest: [], beforeRetry: [], afterResponse: []}
Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
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');
}
]
}
});
(async () => {
const users = await api.get('https://example.com/api/users');
// ...
})();
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 the normalized request and options, the failed response, an error instance and the retry count as arguments. You could, for example, modify request.headers
here.
import ky from 'ky';
(async () => {
await ky('https://example.com', {
hooks: {
beforeRetry: [
async ({request, response, options, errors, retryCount}) => {
const token = await ky('https://example.com/refresh-token');
request.headers.set('Authorization', `token ${token}`);
}
]
}
});
})();
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';
(async () => {
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);
}
}
]
}
});
})();
Type: boolean
Default: true
Throw a HTTPError
for error responses (non-2xx status codes).
Setting this to false
may be useful if you are checking for resource availability and are expecting error responses.
Type: Function
Download progress event handler.
The function receives a progress
and chunk
argument:
progress
object contains the following elements: percent
, transferredBytes
and totalBytes
. If it's not possible to retrieve the body size, totalBytes
will be 0
.chunk
argument is an instance of Uint8Array
. It's empty for the first call.import ky from 'ky';
(async () => {
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`);
}
});
})();
Create a new ky
instance with some defaults overridden with your own.
In contrast to ky.create()
, ky.extend()
inherits defaults from its parent.
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'});
(async () => {
await api.get('users/123');
//=> 'https://example.com/api/users/123'
await api.get('/status', {prefixUrl: ''});
//=> 'https://my-site.com/status'
})();
Type: object
Exposed for instanceof
checks. The error has a response
property with the Response
object.
The error thrown when the request times out.
A Symbol
that can be returned by a beforeRetry
hook to stop the retry. This will also short circuit the remaining beforeRetry
hooks.
import ky from 'ky';
(async () => {
await ky('https://example.com', {
hooks: {
beforeRetry: [
async ({request, response, options, errors, retryCount}) => {
const shouldStopRetry = await ky('https://example.com/api');
if (shouldStopRetry) {
return ky.stop;
}
}
]
}
});
})();
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';
(async () => {
// `multipart/form-data`
const formData = new FormData();
formData.append('food', 'fries');
formData.append('drink', 'icetea');
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';
(async () => {
// `application/x-www-form-urlencoded`
const searchParams = new URLSearchParams();
searchParams.set('food', 'fries');
searchParams.set('drink', 'icetea');
await ky.post(url, {
body: searchParams
});
})();
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);
(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);
}
}
})();
Check out ky-universal
.
Check out ky-universal
.
Either use a test runner that can run in the browser, like Mocha, or use AVA with ky-universal
. Read more.
Upload the index.js
file in this repo somewhere, for example, to your website server, or use a CDN version. Then import the file.
<script type="module">
import ky from 'https://cdn.jsdelivr.net/npm/ky@latest/index.js';
(async () => {
const parsed = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
console.log(parsed.title);
//=> 'delectus aut autem
})();
</script>
Alternatively, you can use the umd.js
file with a traditional <script>
tag (without type="module"
), in which case ky
will be a global.
<script src="https://cdn.jsdelivr.net/npm/ky@latest/umd.js"></script>
<script>
(async () => {
const parsed = await ky('https://jsonplaceholder.typicode.com/todos/1').json();
console.log(parsed.title);
//=> 'delectus aut autem
})();
</script>
got
See my answer here. Got is maintained by the same people as Ky.
axios
?See my answer here.
r2
?See my answer in #10.
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.
The latest version of Chrome, Firefox, and Safari.
Polyfill the needed browser global or just use ky-universal
.
FAQs
Tiny and elegant HTTP client based on the Fetch API
The npm package ky receives a total of 365,115 weekly downloads. As such, ky popularity was classified as popular.
We found that ky demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.