### GET /example Source: https://context7.com/samchungy/zod-openapi/llms.txt An example endpoint demonstrating basic schema generation with date and union types. ```APIDOC ## GET /example An example endpoint demonstrating basic schema generation with date and union types. ### Method GET ### Endpoint /example ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **date** (string) - Formatted as 'date-time' due to override. - **data** (string | number) - Represents a union of string or number. #### Response Example ```json { "date": "2023-10-27T10:00:00.000Z", "data": "example string or 123" } ``` ``` -------------------------------- ### Build Project Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Commands to install dependencies and build the project. ```shell pnpm pnpm build ``` -------------------------------- ### Install zod-openapi Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Install the zod-openapi library along with zod using npm, yarn, or pnpm. ```bash npm install zod zod-openapi # or yarn add zod zod-openapi # or pnpm install zod zod-openapi ``` -------------------------------- ### Add description and example to string schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Use the `.meta()` method on a Zod schema to add standard OpenAPI properties like 'description' and 'example'. ```typescript z.string().meta({ description: 'A text field', example: 'Example value', }); ``` -------------------------------- ### Register OpenAPI Examples Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Provide sample values for schemas using ZodOpenApiExampleObject or by adding them to the components section. ```typescript const example: ZodOpenApiExampleObject = { id: 'userExample', summary: 'A sample user', value: { id: '123', name: 'Jane Doe', email: 'jane@example.com', }, }; // or createDocument({ components: { examples: { userExample: { summary: 'A sample user', value: { id: '123', name: 'Jane Doe', email: 'jane@example.com', }, }, }, }, }); ``` -------------------------------- ### OpenAPI Metadata with .meta() Source: https://context7.com/samchungy/zod-openapi/llms.txt Learn how to use the .meta() method to add descriptions, examples, reusable component IDs, and custom overrides to Zod schemas. ```APIDOC ## .meta() Schema Metadata ### Description Use Zod's native .meta() method to attach OpenAPI metadata to schemas. The 'id' field registers a schema as a reusable component, and any usage will be transformed into a $ref. ### Parameters - **id** (string) - Optional - Registers the schema as a reusable component. - **outputId** (string) - Optional - Custom name for output schema. - **description** (string) - Optional - Description of the field. - **example** (any) - Optional - Example value. - **override** (function/object) - Optional - Custom override for the generated JSON schema. ``` -------------------------------- ### Generated Component Schemas Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Example of the generated component structure when a schema is used in both input and output contexts. ```ts components: { schemas: { Person: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' }, }, }, PersonOutput: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' }, }, additionalProperties: false, }, }, } ``` -------------------------------- ### GET /users/{id} (Components) Source: https://context7.com/samchungy/zod-openapi/llms.txt Retrieves a user by ID, demonstrating the use of registered components like responses and schemas. ```APIDOC ## GET /users/{id} ### Description Retrieves user details by their unique identifier. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user ### Response #### Success Response (200) - **id** (string) - User ID - **name** (string) - User name #### Error Response (404) - **$ref** (string) - #/components/responses/NotFound ``` -------------------------------- ### Example generated OpenAPI JSON Source: https://github.com/samchungy/zod-openapi/blob/master/README.md The resulting JSON structure produced by the createDocument function. ```json { "openapi": "3.1.0", "info": { "title": "My API", "version": "1.0.0" }, "paths": { "/jobs/{jobId}": { "put": { "parameters": [ { "in": "path", "name": "jobId", "description": "A unique identifier for a job", "schema": { "$ref": "#/components/schemas/jobId" } } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "title": { "type": "string", "description": "Job title", "example": "My job" } }, "required": ["title"] } } } }, "responses": { "200": { "description": "200 OK", "content": { "application/json": { "schema": { "type": "object", "properties": { "jobId": { "$ref": "#/components/schemas/jobId" }, "title": { "type": "string", "description": "Job title", "example": "My job" } }, "required": ["jobId", "title"] } } } } } } } }, "components": { "schemas": { "jobId": { "type": "string", "description": "A unique identifier for a job", "example": "12345" } } } } ``` -------------------------------- ### Apply Global Schema Overrides Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Configure global overrides in `createDocument` options to apply transformations to schemas during document creation. This example modifies date schemas to be strings and handles union schema transformations. ```typescript import { createDocument } from 'zod-openapi'; createDocument(document, { override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; } if (def.type === 'union') { jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; } }, }); ``` -------------------------------- ### Register Reusable Components Source: https://context7.com/samchungy/zod-openapi/llms.txt Manually register schemas, responses, security schemes, links, and examples in the components section of the document. ```typescript import * as z from 'zod/v4'; import { createDocument, type ZodOpenApiResponseObject, type ZodOpenApiLinkObject } from 'zod-openapi'; // Schemas for manual registration const ErrorSchema = z.object({ code: z.string(), message: z.string(), }); // Response for manual registration const NotFoundResponse: ZodOpenApiResponseObject = { description: 'Resource not found', content: { 'application/json': { schema: z.object({ error: z.literal('NOT_FOUND'), message: z.string(), }), }, }, }; // Link definition const getUserLink: ZodOpenApiLinkObject = { id: 'GetUserById', operationId: 'getUser', parameters: { userId: '$response.body#/userId' }, description: 'Get the user by ID returned in response', }; const document = createDocument({ openapi: '3.1.0', info: { title: 'API', version: '1.0.0' }, components: { // Manual schema registration schemas: { Error: ErrorSchema, // Will be available as #/components/schemas/Error }, // Manual response registration responses: { NotFound: NotFoundResponse, }, // Security schemes securitySchemes: { oauth2: { type: 'oauth2', flows: { authorizationCode: { authorizationUrl: 'https://auth.example.com/authorize', tokenUrl: 'https://auth.example.com/token', scopes: { 'read:users': 'Read user data', 'write:users': 'Modify user data', }, }, }, }, }, // Links links: { GetUserById: getUserLink, }, // Examples examples: { UserExample: { summary: 'Example user', value: { id: '123', name: 'John Doe', email: 'john@example.com' }, }, }, }, paths: { '/users/{id}': { get: { operationId: 'getUser', requestParams: { path: z.object({ id: z.string() }), }, responses: { '200': { description: 'User found', content: { 'application/json': { schema: z.object({ id: z.string(), name: z.string() }) }, }, }, '404': { $ref: '#/components/responses/NotFound' }, }, }, }, }, }); ``` -------------------------------- ### Attach OpenAPI Metadata to Zod Schemas Source: https://context7.com/samchungy/zod-openapi/llms.txt Use the .meta() method to add descriptions, examples, and component IDs to Zod schemas. The id field enables schema reuse via $ref, while override allows custom JSON schema modifications. ```typescript import * as z from 'zod/v4'; // Basic metadata const EmailSchema = z.string().email().meta({ description: 'User email address', example: 'user@example.com', }); // Register as reusable component with id const UserIdSchema = z.string().uuid().meta({ id: 'userId', description: 'Unique user identifier', example: '550e8400-e29b-41d4-a716-446655440000', }); // Different output ID when used in both request and response const PersonSchema = z.object({ name: z.string(), age: z.number(), }).meta({ id: 'Person', outputId: 'PersonResponse', // Custom name for output schema }); // Custom override using function const UnionSchema = z.union([z.string(), z.number()]).meta({ description: 'String or number value', override: ({ jsonSchema }) => { // Convert anyOf to oneOf jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; }, }); // Custom override using object const DateSchema = z.date().meta({ override: { type: 'string', format: 'date-time', }, }); ``` -------------------------------- ### Add custom format and x-custom-field to datetime schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Use the `.meta()` method to add OpenAPI properties like 'description', 'format', and custom fields like 'x-custom-field'. Note that 'format' is not overridden by a custom value in this example. ```typescript z.string().datetime().meta({ description: 'A date field', format: 'MY-FORMAT', 'x-custom-field': 'custom value', }); ``` -------------------------------- ### Override Schema Type with Meta Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Provide an `override` object within the `.meta()` method to change the schema's type. This example demonstrates overriding the type to `number` for a string schema. ```typescript z.string().meta({ override: { type: number, }, }); ``` -------------------------------- ### Implement Union Behavior with Override Function Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Use an `override` function in `.meta()` to achieve custom behaviors, such as replicating `unionOneOf` by manipulating the `jsonSchema` object. This example converts `anyOf` to `oneOf`. ```typescript z.union([z.string(), z.number()]).meta({ override: ({ jsonSchema }) => { jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; }, }); ``` -------------------------------- ### Run Tests Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Command to execute the test suite. ```shell pnpm test ``` -------------------------------- ### POST /createDocument Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Generates an OpenAPI documentation object from Zod schemas. ```APIDOC ## POST /createDocument ### Description Generates an OpenAPI documentation object based on provided Zod schemas and configuration options. ### Method POST ### Parameters #### Request Body - **doc** (object) - Required - The OpenAPI document configuration including info and paths. - **options** (object) - Optional - Configuration options for document creation, including `override` and `allowEmptySchema`. ### Request Example ```typescript createDocument({ openapi: '3.1.0', info: { title: 'My API', version: '1.0.0' }, paths: { ... } }, { override: ({ jsonSchema, zodSchema, io }) => { ... }, allowEmptySchema: { custom: true } }); ``` ### Response #### Success Response (200) - **document** (object) - The generated OpenAPI 3.1.0 compliant object. ``` -------------------------------- ### Registering Parameters Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Query, Path, Header, and Cookie parameters can be registered using `.meta()` or manually. ```APIDOC ## Registering Parameters Parameters can be registered for use across different parts of your API specification. ### Auto Registration with `param` meta Use the `param` property within `.meta()` to define parameter details. ```typescript const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { id: 'jobRef' }, // Registers this parameter with the ID 'jobRef' }); createDocument({ paths: { '/jobs/{jobId}': { put: { requestParams: { header: z.object({ // Example: registering as a header parameter jobId, }), }, }, }, }, }); ``` ### Verbose Auto Registration Provide more explicit details for parameter registration. ```typescript const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId', id: 'jobRef' }, // Explicitly defines 'in', 'name', and 'id' }); createDocument({ paths: { '/jobs/{jobId}': { put: { parameters: [jobId], // Can also be passed directly to the 'parameters' array }, }, }, }); ``` ### Manual Registration Register parameters directly within the `components.parameters` object. ```typescript const otherJobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId' }, }); createDocument({ components: { parameters: { jobRef: otherJobId, // Manually registers 'otherJobId' as 'jobRef' }, }, }); ``` ``` -------------------------------- ### Schema Generation Comparison Source: https://github.com/samchungy/zod-openapi/blob/master/docs/api.md Comparison of the immediate schema generation in v4 versus the registry-based deferred generation in v5. ```ts // In v4, schema is generated immediately const schema = createMediaTypeSchema({ schema, components, 'output', path, docOpts }); // schema is already populated here console.log(schema); // { type: 'string' } (immediately available) ``` ```ts // In v5, first create a registry const registry = createRegistry(); // Add your schema to the registry (returns a reference) const schema = registry.addSchema({ schema, path, { io: 'output', source: { type: 'mediaType', } } }); console.log(schema); // {} (empty reference) // Generate all schemas and components at once const components = createComponents(registry, docOpts); console.log(schema); // { type: 'string' } (now populated) ``` -------------------------------- ### Lint and Format Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Commands to format and lint the codebase. ```shell # Fix issues pnpm format # Check for issues pnpm lint ``` -------------------------------- ### Registering Parameters Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Register query, path, header, and cookie parameters using the param meta field or manual component registration. ```typescript // Easy auto registration const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { id: 'jobRef' }, }); createDocument({ paths: { '/jobs/{jobId}': { put: { requestParams: { header: z.object({ jobId, }), }, }, }, }, }); // or more verbose auto registration const jobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId', id: 'jobRef' }, }); createDocument({ paths: { '/jobs/{jobId}': { put: { parameters: [jobId], }, }, }, }); // or manual registration const otherJobId = z.string().meta({ description: 'Job ID', example: '1234', param: { in: 'header', name: 'jobId' }, }); createDocument({ components: { parameters: { jobRef: jobId, }, }, }); ``` -------------------------------- ### CreateDocumentOptions Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Configuration options for the `createDocument` function to customize OpenAPI schema generation. ```APIDOC ## CreateDocumentOptions This object allows you to customize the behavior of the `createDocument` function. ### Options - **`override`** (Function) - Override rendered schema with a function. - **`outputIdSuffix`** (string) - Suffix for output schema IDs when the schema is used in both a request and response. Defaults to `''`. - **`allowEmptySchema`** (Object) - Control whether empty schemas are allowed for specific Zod schema types. - **`cycles`** ('ref' | 'throw') - How to handle cycles in schemas. Defaults to `'ref'`. - **`reused`** ('ref' | 'inline') - How to handle reused schemas. Defaults to `'inline'`. ### `override` Function The `override` function allows you to customize the rendered OpenAPI schema. It receives an object with the following properties: - **`jsonSchema`** (Object) - The OpenAPI schema object being generated. You can modify this object. - **`zodSchema`** (ZodType) - The original Zod schema being converted to OpenAPI. - **`io`** ('input' | 'output') - The context in which the schema is being rendered ('input' for request bodies/params, 'output' for responses). #### Example Usage ```typescript createDocument(doc, { override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; return; } if (def.type === 'union') { ctx.jsonSchema.oneOf ??= ctx.jsonSchema.anyOf; delete ctx.jsonSchema.anyOf; return; } }, }); ``` ### `outputIdSuffix` Sets a suffix for output schema IDs when a schema is used in both request and response contexts, useful for distinguishing them. ### `allowEmptySchema` Controls whether the library throws errors for empty schemas (e.g., `z.any()`, `z.unknown()`). #### Example Usage ```typescript createDocument(doc, { allowEmptySchema: { custom: true, // Allow empty schemas for `z.custom()` in all contexts set: { output: true }, // Allow empty schemas for `z.set()` only in an output context }, }); ``` ### `cycles` and `reused` These options are exposed directly from Zod. Refer to the [Zod documentation on cycles](https://zod.dev/json-schema?id=unrepresentable#cycles) for more information. ``` -------------------------------- ### Defining Request Parameters Source: https://context7.com/samchungy/zod-openapi/llms.txt How to define path, query, and header parameters using the requestParams key with Zod object schemas. ```APIDOC ## Request Parameters ### Description Define request parameters using the requestParams key with Zod object schemas for each parameter location (path, query, header, cookie). ### Parameters #### Path Parameters - **path** (ZodObject) - Optional - Schema for path parameters. #### Query Parameters - **query** (ZodObject) - Optional - Schema for query parameters. #### Header Parameters - **header** (ZodObject) - Optional - Schema for header parameters. ``` -------------------------------- ### CreateSchemaOptions for Schema Generation Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Customize schema generation using `CreateSchemaOptions`, including input/output context and pre-defined schema components. ```typescript const { schema, components } = createSchema(job, { // Input/Output context - controls how schemas are generated io: 'input', // 'input' for request bodies/params, 'output' for responses // Component handling schemaComponents: { jobId: z.string() }, // Pre-defined components to use schemaComponentRefPath: '#/definitions/', // Custom path prefix for component references opts: {}, // Create Document Options, }); ``` -------------------------------- ### Document Generation Options Source: https://context7.com/samchungy/zod-openapi/llms.txt Configure how documents are generated with options for overrides, cycles handling, and schema behavior using the `createDocument` function. ```APIDOC ## CreateDocumentOptions - Document Generation Options Configure how documents are generated with options for overrides, cycles handling, and schema behavior. ### Method N/A (Configuration object for `createDocument`) ### Endpoint N/A ### Parameters #### Request Body (Implicit via `createDocument` options) - **override** (function) - Optional - Global override function for all schemas. - **outputIdSuffix** (string) - Optional - Suffix for output schemas. Default: 'Output'. - **cycles** (string) - Optional - How to handle cycles in schemas. Options: 'ref' (default), 'throw'. - **reused** (string) - Optional - How to handle reused schemas. Options: 'inline' (default), 'ref'. - **allowEmptySchema** (object) - Optional - Allow empty schemas for specific types. - **custom** (boolean) - Allow `z.custom()` to render as empty schema. - **set** (object) - Allow `z.set()` only in output context. - **output** (boolean) ### Request Example ```typescript import * as z from 'zod/v4'; import { createDocument } from 'zod-openapi'; const document = createDocument( { openapi: '3.1.0', info: { title: 'API', version: '1.0.0' }, paths: { '/example': { get: { operationId: 'example', responses: { '200': { description: 'OK', content: { 'application/json': { schema: z.object({ date: z.date(), data: z.union([z.string(), z.number()]) }) } } } } } } } }, { // Global override function for all schemas override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; // Convert dates to strings in output context if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; } // Convert all unions to oneOf if (def.type === 'union') { jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; } }, // Suffix for output schemas when used in both contexts outputIdSuffix: 'Response', // Handle cycles in schemas cycles: 'ref', // Handle reused schemas reused: 'inline', // Allow empty schemas for specific types allowEmptySchema: { custom: true, set: { output: true } } } ); ``` ### Response N/A (This is a configuration step, not an API call with a direct response.) ``` -------------------------------- ### createDocument Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Defines API paths, parameters, request bodies, responses, and callbacks using Zod schemas. ```APIDOC ## createDocument ### Description Generates an OpenAPI document by defining paths, parameters, request bodies, responses, and callbacks using Zod schemas. ### Parameters #### Request Body - **paths** (Object) - Required - The API path definitions including methods, requestParams, requestBody, responses, and callbacks. ``` -------------------------------- ### Low-Level Registry Access API Source: https://context7.com/samchungy/zod-openapi/llms.txt For framework integrations and advanced use cases, use the low-level API to manually control schema registration with `createRegistry` and `createComponents`. ```APIDOC ## Advanced API (zod-openapi/api) - Low-Level Registry Access For framework integrations and advanced use cases, use the low-level API to manually control schema registration. ### Method N/A (API for manual schema and parameter registration) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import * as z from 'zod/v4'; import { createRegistry, createComponents } from 'zod-openapi/api'; // Create a registry for manual control const registry = createRegistry(); // Add schemas manually const userSchema = z.object({ id: z.string().uuid(), name: z.string(), email: z.string().email() }); // Add schema to registry (returns empty ref initially) const schemaRef = registry.addSchema( userSchema, ['paths', '/users', 'get', 'responses', '200', 'content', 'application/json', 'schema'], { io: 'output', source: { type: 'mediaType' } } ); // Add parameter const userIdParam = z.string().uuid().meta({ description: 'User ID', param: { in: 'path', name: 'userId' } }); const paramRef = registry.addParameter( userIdParam, ['paths', '/users/{userId}', 'get', 'parameters'], { location: { in: 'path', name: 'userId' } } ); // Generate all components at once (populates refs) const components = createComponents(registry, {}, '3.1.0'); // Now schemaRef is populated with actual schema console.log(schemaRef); // { type: 'object', properties: {...} } console.log(components); // { schemas: {...}, parameters: {...} } ``` ### Response N/A (This API is for building documentation structure, not for direct request/response cycles.) ``` -------------------------------- ### Registering Response Headers Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Response headers can be registered using `.meta()` or manually within `components.headers`. ```APIDOC ## Registering Response Headers Define and register response headers for use in your API specification. ### Auto Registration with `header` meta Use the `header` property within `.meta()` to define header details. ```typescript const header = z.string().meta({ description: 'Job ID', example: '1234', header: { id: 'some-header' }, // Registers this header with the ID 'some-header' }); ``` ### Manual Registration Register headers directly within the `components.headers` object. ```typescript const jobIdHeader = z.string().meta({ description: 'Job ID', example: '1234', }); createDocument({ components: { headers: { someHeaderRef: jobIdHeader, // Manually registers 'jobIdHeader' as 'someHeaderRef' }, }, }); ``` ``` -------------------------------- ### Access Low-Level Registry API Source: https://context7.com/samchungy/zod-openapi/llms.txt Utilize the registry API for manual schema registration and component generation, useful for custom framework integrations. ```typescript import * as z from 'zod/v4'; import { createRegistry, createComponents } from 'zod-openapi/api'; // Create a registry for manual control const registry = createRegistry(); // Add schemas manually const userSchema = z.object({ id: z.string().uuid(), name: z.string(), email: z.string().email(), }); // Add schema to registry (returns empty ref initially) const schemaRef = registry.addSchema( userSchema, ['paths', '/users', 'get', 'responses', '200', 'content', 'application/json', 'schema'], { io: 'output', source: { type: 'mediaType' }, } ); // Add parameter const userIdParam = z.string().uuid().meta({ description: 'User ID', param: { in: 'path', name: 'userId' }, }); const paramRef = registry.addParameter( userIdParam, ['paths', '/users/{userId}', 'get', 'parameters'], { location: { in: 'path', name: 'userId' } } ); // Generate all components at once (populates refs) const components = createComponents(registry, {}, '3.1.0'); // Now schemaRef is populated with actual schema console.log(schemaRef); // { type: 'object', properties: {...} } console.log(components); // { schemas: {...}, parameters: {...} } ``` -------------------------------- ### Generate OpenAPI documentation with createDocument Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Use createDocument to generate an OpenAPI documentation object from Zod schemas. ```typescript import * as z from 'zod/v4'; // or import * as z from 'zod'; if using Zod 4.0.0+ import { createDocument } from 'zod-openapi'; const jobId = z.string().meta({ description: 'A unique identifier for a job', example: '12345', id: 'jobId', }); const title = z.string().meta({ description: 'Job title', example: 'My job', }); const document = createDocument({ openapi: '3.1.0', info: { title: 'My API', version: '1.0.0', }, paths: { '/jobs/{jobId}': { put: { requestParams: { path: z.object({ jobId }) }, requestBody: { content: { 'application/json': { schema: z.object({ title }) }, }, }, responses: { '200': { description: '200 OK', content: { 'application/json': { schema: z.object({ jobId, title }) }, }, }, }, }, }, }, }); ``` -------------------------------- ### Define Request Parameters for OpenAPI Paths Source: https://context7.com/samchungy/zod-openapi/llms.txt Configure path, query, header, and cookie parameters using the requestParams key. Parameters can be defined inline or registered as reusable components using the param metadata. ```typescript import * as z from 'zod/v4'; import { createDocument } from 'zod-openapi'; // Parameter with auto-registration const ApiKeyHeader = z.string().meta({ description: 'API authentication key', param: { id: 'apiKeyHeader', // Registers in components/parameters in: 'header', name: 'X-API-Key', }, }); const document = createDocument({ openapi: '3.1.0', info: { title: 'API', version: '1.0.0' }, paths: { '/users/{userId}': { get: { operationId: 'getUser', requestParams: { path: z.object({ userId: z.string().uuid().meta({ description: 'User ID' }), }), query: z.object({ include: z.enum(['profile', 'posts']).optional().meta({ description: 'Related data to include', }), limit: z.coerce.number().int().min(1).max(100).default(10).meta({ description: 'Maximum results to return', }), }), header: z.object({ 'x-request-id': z.string().optional().meta({ description: 'Request tracking ID', }), }), }, // Alternative: use parameters array directly parameters: [ApiKeyHeader], responses: { '200': { description: 'User found', content: { 'application/json': { schema: z.object({ id: z.string(), name: z.string() }), }, }, }, }, }, }, }, }); ``` -------------------------------- ### Auto Registering Schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Use the meta method to define an id, which automatically creates a reference in the OpenAPI components section. ```typescript const title = z.string().meta({ description: 'Job title', example: 'My job', id: 'jobTitle', // <- new field }); ``` ```json { "$ref": "#/components/schemas/jobTitle" } ``` ```json { "components": { "schemas": { "jobTitle": { "type": "string", "description": "Job title", "example": "My job" } } } } ``` -------------------------------- ### Configure Document Generation Options Source: https://context7.com/samchungy/zod-openapi/llms.txt Use createDocument to define OpenAPI specifications with custom schema overrides, cycle handling, and output formatting. ```typescript import * as z from 'zod/v4'; import { createDocument } from 'zod-openapi'; const document = createDocument( { openapi: '3.1.0', info: { title: 'API', version: '1.0.0' }, paths: { '/example': { get: { operationId: 'example', responses: { '200': { description: 'OK', content: { 'application/json': { schema: z.object({ date: z.date(), data: z.union([z.string(), z.number()]), }), }, }, }, }, }, }, }, }, { // Global override function for all schemas override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; // Convert dates to strings in output context if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; } // Convert all unions to oneOf if (def.type === 'union') { jsonSchema.oneOf = jsonSchema.anyOf; delete jsonSchema.anyOf; } }, // Suffix for output schemas when used in both contexts outputIdSuffix: 'Response', // Default: 'Output' // Handle cycles in schemas cycles: 'ref', // 'ref' (default) or 'throw' // Handle reused schemas reused: 'inline', // 'inline' (default) or 'ref' // Allow empty schemas for specific types allowEmptySchema: { custom: true, // Allow z.custom() to render as empty schema set: { output: true }, // Allow z.set() only in output context }, } ); ``` -------------------------------- ### Configure OpenAPI Version Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Set the OpenAPI version in the document configuration. ```typescript createDocument({ openapi: '3.1.0', }); ``` -------------------------------- ### Generate Complete OpenAPI Document with createDocument Source: https://context7.com/samchungy/zod-openapi/llms.txt Use createDocument to build a full OpenAPI 3.1.x document. Schemas with an id in their metadata are automatically registered as reusable components. ```typescript import * as z from 'zod/v4'; import { createDocument, type ZodOpenApiOperationObject } from 'zod-openapi'; // Define reusable schemas with metadata const JobIdSchema = z.string().uuid().meta({ description: 'A unique identifier for a job', example: '4dd643ff-7ec7-4666-9c88-50b7d3da34e4', id: 'jobId', // Registers as reusable component }); const JobTitleSchema = z.string().nonempty().meta({ description: 'A name that describes the job', example: 'Mid level developer', id: 'jobTitle', }); // Define request/response schemas const CreateJobRequestSchema = z.strictObject({ title: JobTitleSchema, }).meta({ description: 'Create Job Request' }); const CreateJobResponseSchema = z.object({ id: JobIdSchema, }).meta({ description: 'Create Job Response' }); // Define operations const createJobOperation: ZodOpenApiOperationObject = { operationId: 'createJob', summary: 'Create Job', requestBody: { content: { 'application/json': { schema: CreateJobRequestSchema }, }, }, responses: { '201': { id: 'CreateJobResponse', // Register response as component description: 'Successful creation', content: { 'application/json': { schema: CreateJobResponseSchema }, }, }, }, }; // Generate the document const document = createDocument({ openapi: '3.1.0', info: { title: 'Jobs API', version: '1.0.0', description: 'A job management API', }, components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', }, }, }, security: [{ bearerAuth: [] }], paths: { '/jobs': { post: createJobOperation, }, }, }); // Output: Complete OpenAPI 3.1.0 document with schemas auto-registered as components console.log(JSON.stringify(document, null, 2)); ``` -------------------------------- ### createSchema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Creates an OpenAPI Schema Object along with any registered components from a Zod schema. ```APIDOC ## createSchema ### Description Creates an OpenAPI 3.1.0 Schema Object along with any registered components from a Zod schema. ### Parameters #### Request Body - **schema** (ZodSchema) - Required - The Zod schema to convert. - **options** (CreateSchemaOptions) - Optional - Configuration options including 'io' context, 'schemaComponents', and 'schemaComponentRefPath'. ### Response #### Success Response (200) - **schema** (Object) - The generated OpenAPI Schema Object. - **components** (Object) - The registered components. ``` -------------------------------- ### Run Migration Codemod Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Use the provided codemod tool to automate the migration process for TypeScript files. ```bash pnpmx codemod-zod-openapi-v5 'src/**/*.ts' npx codemod-zod-openapi-v5 'src/**/*.ts' ``` -------------------------------- ### Auto Registering Schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Schemas can be automatically registered by using the `.meta()` method with an `id` field. This creates a reference in the OpenAPI components section. ```APIDOC ## Auto Registering Schema This method automatically registers a Zod schema as a reusable component in the OpenAPI documentation. ### Usage Define a Zod schema and include an `id` within the `meta()` configuration. ```typescript const title = z.string().meta({ description: 'Job title', example: 'My job', id: 'jobTitle', // This ID will be used as the component name }); ``` When `createDocument` is called, `title` will be replaced with a reference to the registered schema: ```json { "$ref": "#/components/schemas/jobTitle" } ``` The schema will be defined in the `components.schemas` section: ```json { "components": { "schemas": { "jobTitle": { "type": "string", "description": "Job title", "example": "My job" } } } } ``` ``` -------------------------------- ### POST /subscribe (Callbacks) Source: https://context7.com/samchungy/zod-openapi/llms.txt Defines a subscription endpoint that utilizes a callback for asynchronous webhook notifications. ```APIDOC ## POST /subscribe ### Description Subscribes a client to webhook events by providing a callback URL. ### Method POST ### Endpoint /subscribe ### Parameters #### Request Body - **callbackUrl** (string) - Required - URL to receive webhook events ### Response #### Success Response (201) - **description** (string) - Subscription created ``` -------------------------------- ### Modify document creation with options Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Pass an optional options argument to createDocument to modify global schema generation behavior. ```typescript createDocument(doc, { override: ({ jsonSchema, zodSchema, io }) => { const def = zodSchema._zod.def; if (def.type === 'date' && io === 'output') { jsonSchema.type = 'string'; jsonSchema.format = 'date-time'; } }, allowEmptySchema: { custom: true, }, }); ``` -------------------------------- ### Registering Response Headers Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Register response headers using the header meta field or manual component registration. ```typescript const header = z.string().meta({ description: 'Job ID', example: '1234', header: { id: 'some-header' }, }); // or const jobIdHeader = z.string().meta({ description: 'Job ID', example: '1234', }); createDocument({ components: { headers: { someHeaderRef: jobIdHeader, }, }, }); ``` -------------------------------- ### Declare Request Parameters Traditionally Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Alternatively, declare parameters using the `parameters` key, which will be combined with definitions from `requestParams`. ```typescript createDocument({ paths: { '/jobs/{a}': { put: { parameters: [ z.string().meta({ param: { name: 'job-header', in: 'header', }, }), ], }, }, }, }); ``` -------------------------------- ### Rendered Input Schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md JSON representation of a Zod schema in an input context. ```json { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] } ``` -------------------------------- ### Register OpenAPI Links Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Define relationships between operations using ZodOpenApiLinkObject or by adding them to the components section of the document. ```typescript const link: ZodOpenApiLinkObject = { id: 'getUserById', operationId: 'getUser', parameters: { userId: '$request.path.id', }, description: 'Link to get user by id', }; // or createDocument({ components: { links: { getUserById: { operationId: 'getUser', parameters: { userId: '$request.path.id', }, description: 'Link to get user by id', }, }, }, }); ``` -------------------------------- ### Define Response Schema and Headers Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Set the response schema for a status code and define response headers using the `headers` key. ```typescript createDocument({ paths: { '/jobs': { get: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }) }, }, headers: z.object({ 'header-key': z.string(), }), }, }, }, }, }, }); ``` -------------------------------- ### Update Schema Definitions Source: https://github.com/samchungy/zod-openapi/blob/master/docs/v5.md Replace the deprecated openapi method with the native meta method for schema metadata. ```diff # Replace all schema definitions: - z.string().openapi({ ... }) + z.string().meta({ ... }) ``` -------------------------------- ### Rendered Output Schema Source: https://github.com/samchungy/zod-openapi/blob/master/README.md JSON representation of a Zod schema in an output context, including additionalProperties: false. ```json { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"], "additionalProperties": false } ``` -------------------------------- ### Defining Response Headers Source: https://context7.com/samchungy/zod-openapi/llms.txt How to define response headers using Zod object schemas within the responses object. ```APIDOC ## Response Headers ### Description Define response headers using Zod object schemas with the 'headers' key in response objects. ### Parameters - **headers** (ZodObject) - Optional - Schema defining the response headers. ``` -------------------------------- ### Registering Callbacks Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Callback objects can be registered for reuse in the OpenAPI specification. ```APIDOC ## Registering Callbacks Register callback objects to define webhook interactions. ### Usage Define a callback object and register it using an `id` or manually. ```typescript // Using an ID in the callback object const callback1: ZodOpenApiCallbackObject = { id: 'some-callback', post: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }; // Manual registration const callback2: ZodOpenApiCallbackObject = { post: { responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }; createDocument({ components: { callbacks: { 'some-callback': callback1, // Registered using the ID from the object 'another-callback': callback2, // Manually registered }, }, }); ``` ``` -------------------------------- ### Define Callbacks with Schemas Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Configure callbacks for API endpoints, including request bodies and responses, using nested schema definitions. ```typescript createDocument({ paths: { '/jobs': { get: { callbacks: { onData: { '{$request.query.callbackUrl}/data': { post: { requestBody: { content: { 'application/json': { schema: z.object({ a: z.string() }) }, }, }, responses: { 200: { description: '200 OK', content: { 'application/json': { schema: z.object({ a: z.string() }), }, }, }, }, }, }, }, }, }, }, }, }); ``` -------------------------------- ### Define Request Parameters with createDocument Source: https://github.com/samchungy/zod-openapi/blob/master/README.md Use the `requestParams` key within `method` to define query, path, cookie, and header parameters for an API endpoint. ```typescript createDocument({ paths: { '/jobs/{a}': { put: { requestParams: { path: z.object({ a: z.string() }), query: z.object({ b: z.string() }), cookie: z.object({ cookie: z.string() }), header: z.object({ 'custom-header': z.string() }), }, }, }, }, }); ```