OpenAPI 3.1 & Interactive API Explorer¶
Katal v3 generates comprehensive OpenAPI 3.1.0 specifications directly from your routes, Standard Schemas (Zod, Valibot, ArkType, or Katal native), static controller schemas, and security middleware. It also embeds a modern, zero-dependency interactive documentation explorer powered by Scalar.
1. Quick Start¶
Expose both the OpenAPI 3.1.0 JSON document and the interactive UI with one line:
import { Application, Controller } from "katal";
import type { RequestContext } from "katal";
import { z } from "zod";
const app = new Application({ port: 3000 });
// 1. Define schema using Zod or Standard Schema
const createProductSchema = z.object({
title: z.string().min(2).describe("Product title"),
price: z.number().positive().describe("Price in USD"),
category: z.enum(["electronics", "clothing", "books"]),
});
// 2. Define controller with static schema declaration
class CreateProductController extends Controller {
static schema = {
body: createProductSchema,
};
async handle(ctx: RequestContext) {
const body = ctx.valid<z.infer<typeof createProductSchema>>("body");
return this.created({ id: "prod-1", ...body });
}
}
// 3. Register route with documentation metadata
app.getRouter().post("/api/v1/products", CreateProductController, {
docs: {
summary: "Create a new product catalog item",
description: "Creates and indexes a product for immediate storefront display.",
tags: ["Products"],
},
});
// 4. Expose Scalar UI at /docs and raw JSON at /openapi.json
app.exposeDocs("/docs", "/openapi.json");
await app.listen();
Visit http://localhost:3000/docs in your browser to test endpoints interactively.
2. Zero-Allocation Static Schema Introspection¶
In traditional frameworks, inspecting route schemas requires either instantiating controllers (which can fail if constructor dependencies are missing) or writing duplicate Swagger decorators.
In Katal v3, declaring static schema = { ... } on your controllers allows the router and OpenAPI builder to extract:
- Request body JSON schemas
- Query parameter types and defaults
- Path parameter types
- Header requirements
without instantiating the controller or invoking IoC container logic.
class UpdateOrderController extends Controller {
static schema = {
params: z.object({
id: z.string().uuid().describe("Order UUID"),
}),
body: z.object({
status: z.enum(["pending", "shipped", "delivered"]),
}),
};
constructor(private readonly paymentService: PaymentService) {
super();
// This constructor is NEVER executed during OpenAPI spec generation!
}
async handle(ctx: RequestContext) {
// ...
}
}
3. Automatic Security Schemes (bearerAuth)¶
When any route or route group includes authentication middleware (e.g. ['auth']), Katal automatically generates the Bearer JWT security scheme in the OpenAPI document:
router.get("/api/v1/profile", ProfileController, {
middleware: ["auth"],
docs: { summary: "Get current user profile", tags: ["Users"] },
});
Generated OpenAPI Component:
{
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "Enter your JWT token: Bearer <token>"
}
}
},
"paths": {
"/api/v1/profile": {
"get": {
"security": [{ "bearerAuth": [] }]
}
}
}
}
4. Automatic Path & Query Parameter Detection¶
- Path Parameters: Param segments (e.g.
/users/:idor/organizations/:orgId/teams/:teamId) are converted into OpenAPI{id}parameters within: "path"andrequired: true. - Query Parameters: Extracted from
validation.queryschemas within: "query". - Headers: Extracted from
validation.headersschemas within: "header".
const filterSchema = z.object({
page: z.coerce.number().default(1).describe("Page index"),
limit: z.coerce.number().default(20).describe("Items per page"),
sort: z.enum(["asc", "desc"]).default("desc"),
});
router.get("/api/v1/orders", ListOrdersController, {
validation: { query: filterSchema },
docs: { summary: "List customer orders", tags: ["Orders"] },
});
5. Customizing Document Metadata¶
Pass global specification metadata when calling exposeDocs or getOpenApiDocument:
const openApiDoc = app.getOpenApiDocument({
info: {
title: "Enterprise eCommerce Platform API",
version: "3.2.0",
description: "High-throughput API powered by Katal v3 and Bun.",
contact: {
name: "API Support Team",
email: "api-support@enterprise.com",
url: "https://enterprise.com/developers",
},
license: {
name: "MIT",
url: "https://opensource.org/licenses/MIT",
},
},
servers: [
{ url: "https://api.enterprise.com", description: "Production Cluster" },
{ url: "https://staging-api.enterprise.com", description: "Staging Sandbox" },
{ url: "http://localhost:3000", description: "Local Development" },
],
});
6. Exporting Spec for CI/CD & SDK Generators¶
Export your OpenAPI document programmatically to integrate with tools like openapi-generator, Postman, or Speakeasy:
// scripts/export-openapi.ts
import { app } from "../src/app";
import { writeFileSync } from "node:fs";
await app.boot();
const spec = app.getOpenApiDocument();
writeFileSync("./openapi.json", JSON.stringify(spec, null, 2), "utf-8");
console.log("Successfully exported openapi.json for CI/CD!");