Quick start
This walkthrough makes real requests with a small handwritten OpenAPI-compatible type. In an application, you will normally replace it with a paths type generated by a tool such as openapi-typescript.
1. Install
Fetcher releases are published on the beta dist-tag. Install the selected beta-channel release together with its ky peer dependency.
npm install @ilokesto/fetcher@beta kyCreate quick-start.ts:
import { createFetcher } from '@ilokesto/fetcher/openapi';
type ApiPaths = {
'/users/{id}': {
get: {
parameters: { path: { id: string } };
responses: {
200: { content: { 'application/json': { id: number; name: string } } };
};
};
};
'/posts': {
post: {
requestBody: {
required: true;
content: { 'application/json': { title: string } };
};
responses: {
201: { content: { 'application/json': { id: number; title: string } } };
};
};
};
};
const api = createFetcher<ApiPaths>({
prefixUrl: 'https://jsonplaceholder.typicode.com',
});
const user = await api
.get('/users/{id}', {
params: { path: { id: '1' } },
})
.json();
console.log(user.name);Run it with your TypeScript runner (for example, npx tsx quick-start.ts). It prints Leanne Graham. The path template is expanded before it reaches ky, and user is inferred as { id: number; name: string } from the JSON response.
The remaining examples are fragments that extend the api client above. Generated paths types provide the same contract for your own endpoints.
Send a typed body
const post = await api
.post('/posts', {
json: {
title: 'Typed facade',
},
})
.json();json, formData, and formUrlEncoded are mutually exclusive shortcut body shapes. Use the third argument only for normal ky options such as timeout, signal, hooks, context, or explicit override bodies.
Keep ky composition
const authed = api.extend({
headers: {
Authorization: `Bearer ${token}`,
},
});
await authed.get('/users/{id}', {
params: { path: { id: '42' } },
});create, extend, hooks, retry, timeout, custom fetch, and HTTPError behavior stay ky-compatible. fetcher prepares OpenAPI-shaped input, then delegates the request to the underlying KyInstance.
Use safe when you do not want exceptions
const result = await api.safe.get('/users/{id}', {
params: { path: { id: '42' } },
});
if (result.ok) {
result.data;
} else {
result.error;
result.response;
}The default surface still throws like ky; safe converts the same request into a discriminated result.
Next steps
- Read Core concepts for the ky-first mental model.
- Use Generated OpenAPI types to replace the handwritten type.
- Check Grouped request for exact shortcut input rules.