Skip to content

ApiDefinition

ApiDefinition is the type (and class) returned by defineApi. It holds the map of your routes plus the cache, optional OpenAPI info, and optional logger. Its generic parameter carries the fully-inferred shape of your API, which is what the client consumes via typeof api for end-to-end type safety.

You rarely construct an ApiDefinition yourself — you build one by chaining .route() calls on defineApi(). You do pass it to other functions in the package.

class ApiDefinition<Routes extends Record<Path, unknown>> {
routes: Routes;
cache: Cache;
oas?: { title: string; version: string };
logger?: Logger;
invalidate(tags: string[]): Promise<void>;
route(path, route): ApiDefinition<Routes & { [path]: ... }>;
}
Property Type Description
routes Routes The map of registered route paths to their handler modules. Referenced as typeof api (or typeof api.routes) when constructing a client.
cache Cache The cache / pub-sub instance. Pass it to streamRevalidatedTags when wiring the invalidation stream by hand.
oas { title, version } | undefined The OpenAPI info, when provided to defineApi. Enables the /__tapi/openapi.json route.
logger Logger | undefined The error logger used by the request handler.

Registers a route and returns the same instance re-typed to include it. See defineApi.route().

Invalidates cached responses tagged with any of tags by calling cache.delete(tags). Useful for purging cache entries from outside a request handler (for example a cron job or webhook).

await api.invalidate(["books"]);
api.ts
export const api = defineApi().route("/books", import("./routes/books"));
// client.ts
import { createFetchClient } from "@toapi/client";
import type { api } from "./api";
export const client = createFetchClient<typeof api.routes>("/api");