Skip to navigation

what is-.openapi()?

.openapi() is a helper method that Zod gets after you call extendZodWithOpenApi(z).
What it does: lets you attach OpenAPI-specific metadata to a Zod schema (or field) for docs generation. It doesn’t change validation—it’s purely for the OpenAPI output. Quick points:

  • Add docs to fields

    import { z } from ‘zod’; import { extendZodWithOpenApi } from ‘@asteasolutions/zod-to-openapi’; extendZodWithOpenApi(z);

    const UserCreateBody = z.object({ name: z.string().min(1).openapi({ description: ‘Full name’, example: ‘Jane Doe’ }), age: z.number().int().openapi({ description: ‘Age in years’, example: 30 }), });

  • Name a component (schema)

    const User = z.object({ id: z.string().uuid().openapi({ example: ‘123e4567-e89b-12d3-a456-426614174000’ }), name: z.string().min(1), }).openapi(‘User’); // shows up under components/schemas.User

  • File upload example (docs only)

    const UploadBody = z.object({ file: z.string().openapi({ format: ‘binary’, description: ‘File to upload’ }), }).openapi(‘UploadBody’);

  • What it’s not

    • Not a runtime validator. Don’t pass the .openapi()-decorated output directly to Fastify’s schema expecting JSON Schema, use the plain Zod for validation; use the OpenAPI generator/registry for docs.