@nijesmik/openapi-ky
v2.0.1
Published
Type-safe ky client driven by an OpenAPI schema.
Readme
@nijesmik/openapi-ky
Type-safe ky client driven by an OpenAPI schema.
Install
npm install @nijesmik/openapi-ky kyky is a peer dependency. Generate the paths type from your OpenAPI document with openapi-typescript and import it as shown below.
Usage
import createClient from '@nijesmik/openapi-ky';
import type { paths } from './schema'; // generated by openapi-typescript
const client = createClient<paths>({ baseUrl: 'https://api.example.com' });
// GET with path params
const user = await client
.get('/users/{userId}', { params: { userId: 1 } })
.json();
// POST with json body
const created = await client
.post('/posts', { json: { title: 'Hello', content: 'World' } })
.json();params is a path-template substitution field added on top of ky (e.g. {userId} → 1). All other ky options (headers, searchParams, hooks, retry, timeout, …) pass through. See ky docs.
Configuring a default method
Optional. By default the client dispatches GET when called directly (client(path, opts)). To bind a different default, pass it as the second generic and as defaultOptions.method:
import createClient from '@nijesmik/openapi-ky';
import type { paths } from './schema';
const client = createClient<paths, 'post'>({
baseUrl: 'https://api.example.com',
method: 'post',
});
await client('/posts', { json: { title: 'Hello' } }).json();The shortcut methods (client.get, client.post, …) always use the method named on the shortcut, regardless of the instance default.
Method resolution: options.method (per call) → defaultOptions.method (instance) → 'get' (ky's fallback).
Type helpers
import type { RequestBody, ResponseBody } from '@nijesmik/openapi-ky';
import type { paths } from './schema';
type CreatePostBody = RequestBody<paths, '/posts', 'post'>; // method is required
type User = ResponseBody<paths, '/users/{userId}'>; // method defaults to 'get'Also exported: Client, PathsFor, PathParams, Options, OptionsWithRequiredMethod, JsonField, KyOptions, SearchParams, HttpMethod.
License
MIT
