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();Signature
Section titled “Signature”function generateOpenAPISchema( apiDefinition: ApiDefinition<Routes>, options: { info: { title: string; version: string } },): Promise<OpenAPIDocument>;Parameters
Section titled “Parameters”apiDefinition
Section titled “apiDefinition”Type: ApiDefinition
The API definition object returned by defineApi.
options
Section titled “options”| Property | Type | Description |
|---|---|---|
info |
{ title: string; version: string } |
Required. Metadata for the API specification. |
Schema mapping
Section titled “Schema mapping”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) |
Path parameter transformation
Section titled “Path parameter transformation”Toapi uses colon syntax (e.g. /users/:id) for path parameters. generateOpenAPISchema automatically converts this to OpenAPI curly-brace syntax (e.g. /users/{id}).
Response schemas
Section titled “Response schemas”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 () => { // ... },);Related
Section titled “Related”defineApi— passoasto serve the document automatically.createRequestHandler— mounts the OpenAPI route.