Skip to content

Create type-safe fetcher from OpenAPI 3 specs, with any fetch client, such as axios, ky and so on.

License

Notifications You must be signed in to change notification settings

type-safe-dx/openapi-typescript-any-client

Repository files navigation

openapi-typescript-any-client

Create type-safe fetcher with any fetch client, such as axios, ky and so on.

codecov

demo

Usage

Install

npm i -D @kiyoshiro/openapi-typescript-any-client

Generate code

openapi-typescript-any-client ./openapi.yaml -o generated.ts

Define your own fetcher with the generated code

path pattern operationId pattern
// fetcher.ts
import { createBaseFetcher } from "./generated";

// standard fetch
export const fetcher = createBaseFetcher((path, { method, body }) =>
  fetch("http://localhost:3000" + path, {
    method,
    body: JSON.stringify(body),
  }).then((res) => res.json())
);

// axios
export const fetcher = createBaseFetcher((path, { method, body }) =>
  axios({
    baseURL: "http://localhost:3000",
    url: path,
    method,
    data: body,
  }).then((res) => res.data)
);

// ky
export const fetcher = createBaseFetcher((path, { method, body }) =>
  ky(path, {
    prefixUrl: "http://localhost:3000",
    url: path,
    method,
    json: body,
  }).json()
);
// fetcher.ts
import { createOperationIdFetcher } from "./generated";

// standard fetch
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  fetch("http://localhost:3000" + path, {
    method,
    body: JSON.stringify(body),
  }).then((res) => res.json())
);

// axios
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  axios({
    baseURL: "http://localhost:3000",
    url: path,
    method,
    data: body,
  }).then((res) => res.data)
);

// ky
export const fetcherObj = createOperationIdFetcher((path, { method, body }) =>
  ky(path, {
    prefixUrl: "http://localhost:3000",
    url: path,
    method,
    json: body,
  }).json()
);

Use the fetcher created above (It's type-safe!)

path pattern operationId pattern
const res = await fetcher.get("/users", {
  query: { per: 10, page: 0 },
});
// `listUsers` comes from operationId
// in your OpenAPI schema
const res = await fetcherObj.listUsers({
  query: { per: 10, page: 0 },
});