Skip to content

generateOpenAPISchema

The generateOpenAPISchema function generates an OpenAPI 3.1 specification from your defineApi definition. This is useful for generating documentation (like Swagger UI) or client SDKs for other languages.

import { generateOpenAPISchema } from "@toapi/server";
import { api } from "./api"; // Your ApiDefinition
async function main() {
const openApiDoc = await generateOpenAPISchema(api, {
info: {
title: "My API",
version: "1.0.0",
},
});
console.log(JSON.stringify(openApiDoc, null, 2));
}
main();
function generateOpenAPISchema(
apiDefinition: ApiDefinition<Routes>,
options: { info: { title: string; version: string } },
): Promise<OpenAPIDocument>;

Type: ApiDefinition

The API definition object returned by defineApi.

Property Type Description
info { title: string; version: string } Required. Metadata for the API specification.

The function iterates through all routes in your API and maps the Zod schemas from your defineHandler calls to OpenAPI schema objects.

Toapi schema OpenAPI location
params parameters (in path)
query parameters (in query)
body requestBody (content: application/json)
response responses.200 (content: application/json)

Toapi uses colon syntax (e.g. /users/:id) for path parameters. generateOpenAPISchema automatically converts this to OpenAPI curly-brace syntax (e.g. /users/{id}).

To get the most out of the generated specification, provide a response schema in your defineHandler options. It describes the success-response shape in the OpenAPI document (and is validated at runtime). When omitted, the response is described as z.any().

export const GET = defineHandler(
{
authorize: () => true,
// Define response schema for OpenAPI
response: z.object({
id: z.string(),
name: z.string(),
}),
},
async () => {
// ...
},
);