### Install hono-zod-openapi with deno Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/getting-started.md Install the library using deno. ```sh deno add jsr:@paolostyle/hono-zod-openapi ``` -------------------------------- ### Install hono-zod-openapi with bun Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/getting-started.md Install the library using bun. ```sh bun add hono-zod-openapi ``` -------------------------------- ### Minimal Hono App with OpenAPI Middleware Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/README.md This example demonstrates a basic Hono application setup using the openApi middleware for route definition, request parameter validation, and type-safe response building. It also shows how to generate and serve the OpenAPI document. ```typescript import { Hono } from 'hono'; import * as z from 'zod'; import { createOpenApiDocument, openApi } from 'hono-zod-openapi'; const app = new Hono().get( '/users/:id', openApi({ tags: ['Users'], responses: { 200: z.object({ id: z.string(), name: z.string() }), 404: z.object({ error: z.string() }), }, request: { param: z.object({ id: z.string() }), }, }), (c) => { const { id } = c.req.valid('param'); if (id === 'unknown') { return c.var.res(404, { error: 'User not found' }); } return c.var.res(200, { id, name: 'John Doe' }); }, ); createOpenApiDocument(app, { info: { title: 'Users API', version: '1.0.0' }, }); // GET /doc now serves the OpenAPI document ``` -------------------------------- ### Install hono-zod-openapi with yarn Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/getting-started.md Install the library using yarn. ```sh yarn add hono-zod-openapi ``` -------------------------------- ### Install hono-zod-openapi with pnpm Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/getting-started.md Install the library using pnpm. ```sh pnpm add hono-zod-openapi ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/contributing.md Run these commands to set up the project locally. Corepack is required for PNPM installation. ```sh corepack enable corepack install pnpm i ``` -------------------------------- ### Install hono-zod-openapi with npm Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/README.md Use this command to install the library using npm. ```bash npm install hono-zod-openapi ``` -------------------------------- ### Install hono-zod-openapi with JSR Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/README.md Use this command to install the library using JSR. ```bash jsr add @paolostyle/hono-zod-openapi ``` -------------------------------- ### Bearer Authentication Example Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/recipes.md Demonstrates how to configure and use Bearer authentication for an API endpoint using Hono Zod OpenAPI. This setup can be applied globally or per-route. ```typescript const app = new Hono().get( '/example', openApi({ responses: { 200: z.object({}), }, security: [{ bearerAuth: [] }], }), async (c) => { return c.json({}, 200); }, ); createOpenApiDocument(app, { info: { title: 'Some API', version: '0.0.1', }, components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', }, }, }, // if you use bearer auth in every endpoint, you can add // this here instead of adding `security` to every route: // security: [{ bearerAuth: [] }], }); ``` -------------------------------- ### Path Parameter Conversion Examples Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/createOpenApiDocument.md Provides examples of how Hono path parameters are converted to OpenAPI path parameters. This includes standard parameters, optional parameters, and parameters with regular expressions. ```text - /users/:id → /users/{id} - /users/:id? → /users/{id} - /files/:name{.*} → /files/{name} ``` -------------------------------- ### Quick Example of hono-zod-openapi Usage Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/README.md This example demonstrates how to use the `openApi` middleware and `createOpenApiDocument` function to create a type-safe API endpoint for user retrieval. ```typescript import { Hono } from 'hono'; import * as z from 'zod'; import { createOpenApiDocument, openApi } from 'hono-zod-openapi'; const app = new Hono().get( '/user', openApi({ tags: ['User'], responses: { 200: z.object({ hi: z.string() }), }, request: { query: z.object({ id: z.string() }), }, }), (c) => { const { id } = c.req.valid('query'); return c.var.res(200, { hi: id }); }, ); createOpenApiDocument(app, { info: { title: 'Example API', version: '1.0.0', }, }); ``` -------------------------------- ### Usage Examples: Parsing Different Call Patterns Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/response-parsing.md Provides practical examples of using `parseResArgs` with various argument combinations, including payload only, status and payload, payload and headers, and all three. ```typescript import { parseResArgs } from 'hono-zod-openapi'; // Pattern 1: Just payload const parsed1 = parseResArgs([{ id: '1', name: 'John' }]); console.log(parsed1); // { status: 200, payload: { id: '1', name: 'John' } } ``` ```typescript // Pattern 2: Status and payload const parsed2 = parseResArgs([201, { id: '1' }]); console.log(parsed2); // { status: 201, payload: { id: '1' } } ``` ```typescript // Pattern 3: Payload and headers const parsed3 = parseResArgs([ { id: '1' }, { 'x-created': 'true' } ]); console.log(parsed3); // { status: 200, payload: { id: '1' }, headers: { 'x-created': 'true' } } ``` ```typescript // Pattern 4: Status, payload, and headers const parsed4 = parseResArgs([ 201, { id: '1' }, { 'Location': '/users/1' } ]); console.log(parsed4); // { status: 201, payload: { id: '1' }, headers: { 'Location': '/users/1' } } ``` -------------------------------- ### Basic GET Request with Query Parameters Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/openApi-middleware.md Demonstrates how to use the openApi middleware for a GET request with parameter validation. It defines response schemas and validates incoming parameters. ```typescript import { Hono } from 'hono'; import * as z from 'zod'; import { openApi } from 'hono-zod-openapi'; const app = new Hono().get( '/users/:id', openApi({ tags: ['Users'], summary: 'Get user by ID', responses: { 200: z.object({ id: z.string(), name: z.string(), email: z.string().email(), }).meta({ examples: [{ id: '1', name: 'John', email: 'john@example.com' }] }), 404: z.object({ error: z.string() }), }, request: { param: z.object({ id: z.string() }), }, }), (c) => { const { id } = c.req.valid('param'); // Type-safe response with status code validation return c.var.res(200, { id, name: 'John Doe', email: 'john@example.com', }); }, ); ``` -------------------------------- ### Minimal Hono OpenAPI Document Configuration Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Sets up a Hono application with a basic GET route and creates an OpenAPI document with minimal required info. ```typescript import { Hono } from 'hono'; import { createOpenApiDocument, openApi } from 'hono-zod-openapi'; import * as z from 'zod'; const app = new Hono() .get( '/hello', openApi({ responses: { 200: z.object({ message: z.string() }), }, }), (c) => c.var.res(200, { message: 'Hello' }), ); createOpenApiDocument(app, { info: { title: 'My API', version: '1.0.0', }, }); ``` -------------------------------- ### Response Configuration with Wildcard Patterns Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Example of configuring responses using wildcard patterns ('4XX', '5XX') and a default catch-all for unspecified status codes. ```typescript // With wildcard patterns { 200: z.object({ data: z.unknown() }), '4XX': z.object({ error: z.string() }), '5XX': z.object({ error: z.string() }), } // With default catch-all { 200: z.object({ data: z.unknown() }), 'default': z.object({ error: z.string() }), } ``` -------------------------------- ### Usage Example for normalizeResponse Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates normalizing different response formats including Zod objects, simple objects with media types, and reference objects. ```typescript import { normalizeResponse } from 'hono-zod-openapi'; import * as z from 'zod'; // Normalize different response formats const userResponse = normalizeResponse( z.object({ id: z.string(), name: z.string(), }), 200, '/users/{id}', ); const htmlResponse = normalizeResponse( { schema: z.string(), mediaType: 'text/html', }, 200, '/page', ); const refResponse = normalizeResponse( { $ref: '#/components/schemas/User' }, 200, '/users/{id}', ); ``` -------------------------------- ### Quick Example: Hono App with OpenAPI Docs Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/getting-started.md Integrates hono-zod-openapi to define a user route with query parameter validation and OpenAPI documentation. The generated OpenAPI document is served at the '/doc' route. ```ts import { Hono } from 'hono'; import * as z from 'zod'; import { createOpenApiDocument, openApi } from 'hono-zod-openapi'; const app = new Hono().get( '/user', openApi({ tags: ['User'], responses: { 200: z .object({ hi: z.string() }) .meta({ examples: [{ hi: 'user' }] }), }, request: { query: z.object({ id: z.string() }), }, }), (c) => { // validates query params against schema in runtime const { id } = c.req.valid('query'); // payload is validated on type level against responses return c.var.res(200, { hi: id }); }, ); // this will add a `GET /doc` route to the `app` router createOpenApiDocument(app, { info: { title: 'Example API', version: '1.0.0', }, }); ``` ```json { "info": { "title": "Example API", "version": "1.0.0" }, "openapi": "3.1.0", "paths": { "/user": { "get": { "tags": ["User"], "parameters": [ { "in": "query", "name": "id", "required": true, "schema": { "type": "string" } } ], "responses": { "200": { "content": { "application/json": { "schema": { "examples": [ { "hi": "user" } ], "properties": { "hi": { "type": "string" } }, "required": ["hi"], "type": "object", "additionalProperties": false } } }, "description": "200 OK" } } } } } } ``` -------------------------------- ### OpenAPI Middleware for Endpoints Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/api-reference.md The `openApi` middleware is used to document a given endpoint. Refer to the usage guide for detailed examples of the `request` and `responses` fields. ```typescript function openApi( operation: HonoOpenApiOperation, ): MiddlewareHandler, P, Values>; ``` -------------------------------- ### Documenting Response Codes with Metadata and Descriptions Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/errors.md Enhance OpenAPI documentation by using Zod's `.meta()` for examples and providing explicit descriptions for response codes. ```typescript openApi({ responses: { 200: z.object({ id: z.string(), name: z.string(), }).meta({ examples: [{ id: '1', name: 'John' }], }), 400: { schema: z.object({ error: z.string() }), description: 'Invalid request parameters', }, 404: { schema: z.object({ error: z.string() }), description: 'User not found', }, }, }) ``` -------------------------------- ### No Content Response (204) Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Example of returning a 204 No Content response using `c.var.res` with `null` payload. ```typescript (openApi({ responses: { 204: { description: 'No content' }, }, }), (c) => c.var.res(204, null)); ``` -------------------------------- ### HonoOpenApiResponses Example Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/types.md Demonstrates defining responses for various HTTP status codes, including specific codes like 200 and 400, wildcard codes like '5XX', and a general 'default' response. ```typescript { 200: z.object({ id: z.string() }), 201: z.object({ id: z.string(), created: z.boolean() }), 400: z.object({ error: z.string() }), '5XX': z.object({ error: z.string() }), 'default': z.object({ error: z.string() }) } ``` -------------------------------- ### HonoOpenApiRequestSchemas Examples Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/types.md Illustrates how to define request schemas for different validation targets, including simple schemas, schemas with disabled runtime validation, and combinations of multiple targets. ```typescript // Simple schema - validates at runtime and documents { json: z.object({ name: z.string() }) } // With validation control - only document without runtime validation { json: { schema: z.object({ name: z.string() }), validate: false } } // Multiple targets { json: z.object({ email: z.string() }), query: z.object({ filter: z.string().optional() }), param: z.object({ id: z.string() }) } ``` -------------------------------- ### HonoOpenApiResponseObject - Raw Zod Schema Example Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/types.md Shows how to define a response using only a Zod schema. The content type is inferred, and a default description is used. This is the simplest way to define a response. ```typescript { 200: z.object({ ok: z.boolean() }) } ``` -------------------------------- ### HonoOpenApiResponseObject - Simple Response Object Example Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/types.md Demonstrates defining a response using the SimpleResponseObject structure, specifying the schema, description, and media type. This provides more explicit control over the response details. ```typescript { 200: { schema: z.string(), description: 'HTML page', mediaType: 'text/html' } } ``` -------------------------------- ### Basic OpenAPI Document Generation Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/createOpenApiDocument.md Generates a basic OpenAPI document for a Hono application. Ensure the 'openApi' middleware is used for routes to be included. The document will be automatically served at GET /doc. ```typescript import { Hono } from 'hono'; import * as z from 'zod'; import { createOpenApiDocument, openApi } from 'hono-zod-openapi'; const app = new Hono() .get( '/users/:id', openApi({ tags: ['Users'], responses: { 200: z.object({ id: z.string(), name: z.string() }), }, request: { param: z.object({ id: z.string() }), }, }), (c) => c.var.res(200, { id: '1', name: 'John' }), ); createOpenApiDocument(app, { info: { title: 'My API', version: '1.0.0', }, }); // GET /doc now returns the OpenAPI JSON ``` -------------------------------- ### Response Configuration with Specific Status Codes Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Example of configuring responses for specific HTTP status codes (200, 201, 400, 404, 500) using Zod schemas. ```typescript // Specific status codes { 200: z.object({ id: z.string() }), 201: z.object({ id: z.string() }), 400: z.object({ error: z.string() }), 404: z.object({ error: z.string() }), 500: z.object({ error: z.string() }), } ``` -------------------------------- ### Generated OpenAPI JSON Document Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/api-reference.md This JSON document represents the OpenAPI specification generated from the `defineOpenApiOperation` example. It details the path, method, parameters, request body, and responses. ```json { "info": { "title": "Example API", "version": "1.0.0" }, "openapi": "3.1.0", "paths": { "/user": { "get": { "parameters": [ { "in": "cookie", "name": "session", "required": true, "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "properties": { "email": { "type": "string" } }, "required": ["email"], "type": "object", "additionalProperties": false } } } }, "responses": { "200": { "content": { "application/json": { "schema": { "properties": { "name": { "type": "string" } }, "required": ["name"], "type": "object", "additionalProperties": false } } }, "description": "200 OK" }, "400": { "content": { "application/xml": { "schema": { "properties": { "message": { "type": "string" } }, "required": ["message"], "type": "object", "additionalProperties": false } } }, "description": "Custom description" }, "401": { "content": { "application/json": { "schema": { "properties": { "message": { "type": "string" } }, "required": ["message"], "type": "object", "additionalProperties": false } } }, "description": "Required description" }, "404": { "content": { "application/json": { "schema": { "properties": { "message": { "type": "string" } }, "required": ["message"], "type": "object", "additionalProperties": false } } }, "description": "Not found" } }, "tags": ["User"] } } } } ``` -------------------------------- ### Type Coercion with `parseResArgs` Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/response-parsing.md Shows examples of `parseResArgs` accepting `unknown[]` and handling various argument types for status, payload, and headers without explicit type coercion. ```typescript // All of these work without coercion: parseResArgs([200, { data: 'x' }]); // number first → (status, payload) parseResArgs(['200', { data: 'x' }]); // string first → (payload, headers) parseResArgs([{ data: 'x' }, undefined]); // (payload, headers) parseResArgs([null, { data: 'x' }]); // null first → (payload, headers) ``` -------------------------------- ### Basic JSON response with status 200 Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/typed-response.md Demonstrates a basic GET endpoint that returns a JSON response with a default 200 status code. It defines the expected parameter and response schemas. ```APIDOC ## GET /users/:id ### Description Handles a GET request to retrieve user information by ID, returning a JSON object with user details. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. #### Request Body None ### Response #### Success Response (200) - **id** (string) - The user's ID. - **name** (string) - The user's name. #### Response Example ```json { "id": "user-id", "name": "John Doe" } ``` ``` -------------------------------- ### Resolve Response Content Type Examples Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/utility-functions.md Demonstrates how to use `resolveResponseContentType` with various input formats to determine the response content type. This function is useful for setting appropriate headers and content negotiation in Hono applications. ```typescript import { resolveResponseContentType } from 'hono-zod-openapi'; import * as z from 'zod'; // Raw schema resolveResponseContentType(z.string()); // 'text/plain' ``` ```typescript // Simple object resolveResponseContentType({ schema: z.string(), mediaType: 'text/html' }); // 'text/html' ``` ```typescript // OpenAPI object with multiple formats resolveResponseContentType({ description: 'Response', content: { 'application/json': { schema: z.object({}) }, 'text/plain': { schema: z.string() } } }); // ['application/json', 'text/plain'] ``` ```typescript // Reference resolveResponseContentType({ $ref: '#/components/schemas/User' }); // null ``` -------------------------------- ### Example of Values Type Resolution Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/types.md Illustrates how the `Values` type resolves to a specific structure based on provided request schemas for JSON and query parameters. This shows the expected shape of validated request data. ```typescript // Given request schemas: { json: z.object({ name: z.string() }), query: z.object({ filter: z.string().optional() }) } // Values type resolves to: { in: { json: { name: string }, query: { filter?: string } }, out: { json: { name: string }, query: { filter?: string } } } ``` -------------------------------- ### Get Post by ID Endpoint Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Defines a GET endpoint to retrieve a post by its ID, demonstrating the reuse of a 'not found' error response configuration. ```APIDOC ## GET /posts/:id ### Description Retrieves a post by its unique identifier. ### Method GET ### Endpoint /posts/:id ### Parameters #### Path Parameters - **id** (string) - Required - Post ID (UUID) ### Response #### Success Response (200) - **id** (string) - Post ID (UUID) - **title** (string) - Post title - **content** (string) - Post content - **createdAt** (string) - Timestamp of creation #### Response Example { "id": "f0e9d8c7-b6a5-4321-fedc-ba9876543210", "title": "Example Post", "content": "This is the content of the example post.", "createdAt": "2023-10-27T10:00:00Z" } #### Error Response (404) - **error** (string) - Error message indicating the resource was not found #### Error Response (500) - **error** (string) - Internal server error message ``` -------------------------------- ### Get User by ID Endpoint Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Defines a GET endpoint to retrieve a user by their ID, utilizing reusable response configurations for success and error cases. ```APIDOC ## GET /users/:id ### Description Retrieves a user by their unique identifier. ### Method GET ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - User ID (UUID) ### Response #### Success Response (200) - **id** (string) - User ID (UUID) - **name** (string) - User full name - **email** (string) - User email address - **createdAt** (string) - Timestamp of creation #### Response Example { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "name": "John Doe", "email": "john.doe@example.com", "createdAt": "2023-10-27T10:00:00Z" } #### Error Response (404) - **error** (string) - Error message indicating the user was not found #### Error Response (500) - **error** (string) - Internal server error message ``` -------------------------------- ### POST /users Route Handler with Response Parsing Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/response-parsing.md Demonstrates using `openApi` middleware to define request and response schemas, and how to use `c.var.res` with different argument combinations within a route handler. ```typescript import { openApi, } from 'hono-zod-openapi'; import * as z from 'zod'; app.post( '/users', openApi({ responses: { 201: z.object({ id: z.string() }), 400: z.object({ error: z.string() }), }, request: { json: z.object({ name: z.string() }), }, }), (c) => { const { name } = c.req.valid('json'); // These are all equivalent to res() internally: // Default 200 status if (name === 'admin') { return c.var.res({ id: '0' }); // Parsed as (payload) -> status 200 } // Explicit status if (name) { return c.var.res(201, { id: 'new-123' }); // Parsed as (status, payload) } // With headers return c.var.res( 201, { id: 'new-456' }, { 'Location': '/users/new-456' } // Parsed as (status, payload, headers) ); }, ); ``` -------------------------------- ### JSON Response with Schema Inference Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Example of returning a JSON response where the content type is inferred as `application/json` from the Zod object schema. ```typescript (openApi({ responses: { 200: z.object({ name: z.string() }), }, }), (c) => c.var.res(200, { name: 'John' })); ``` -------------------------------- ### Full OpenAPI Response Object Schema Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Defines a comprehensive response object including content with JSON schema, examples, and detailed headers. ```typescript responses: { 200: { description: 'User found', content: { 'application/json': { schema: z.object({ id: z.string() }), examples: { default: { value: { id: '123' } }, }, }, }, headers: { 'X-RateLimit-Remaining': { description: 'Requests remaining', schema: z.string(), }, }, }, } ``` -------------------------------- ### Text Response with Schema Inference Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Example of returning a plain text response where the content type is inferred as `text/plain` from the Zod string schema. ```typescript (openApi({ responses: { 200: z.string(), }, }), (c) => c.var.res(200, 'Hello World')); ``` -------------------------------- ### Main Entry Point Exports Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/README.md Exports from the main entry point of the library, including functions and types for OpenAPI document creation and middleware. ```typescript // Functions export { createOpenApiDocument } from './createOpenApiDocument.ts'; export { createOpenApiMiddleware, openApi, defineOpenApiOperation } from './openApi.ts'; // Types export type { HonoOpenApiDocument } from './types.ts'; export type { HonoOpenApiOperation } from './types.ts'; export type { HonoOpenApiRequestSchemas } from './types.ts'; export type { HonoOpenApiResponses } from './types.ts'; export type { HonoOpenApiResponseObject } from './types.ts'; ``` -------------------------------- ### Full API Configuration with All Features Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Configures a POST endpoint for creating users with detailed OpenAPI specifications, including request body validation, multiple response types, and security schemes. It also generates the OpenAPI document with comprehensive info, servers, tags, and security components. ```typescript const app = new Hono() .post( '/users', openApi({ tags: ['Users'], summary: 'Create a new user', description: 'Creates a new user account in the system', operationId: 'createUser', request: { json: z.object({ name: z.string().min(1).describe('User full name'), email: z.string().email().describe('User email address'), age: z.number().int().min(18).optional().describe('User age'), }), }, responses: { 201: { schema: z.object({ id: z.string().uuid(), name: z.string(), email: z.string(), createdAt: z.string().datetime(), }), description: 'User successfully created', }, 400: { schema: z.object({ error: z.string(), details: z.record(z.string(), z.string()), }), description: 'Validation error', }, 409: { schema: z.object({ error: z.string().describe('Email already in use'), }), description: 'Email already exists', }, 500: z.object({ error: z.string() }), }, security: [{ bearerAuth: [] }], }), async (c) => { const { name, email } = c.req.valid('json'); const user = await db.users.create({ name, email }); return c.var.res(201, user); }, ); createOpenApiDocument( app, { info: { title: 'User Management API', version: '2.0.0', description: 'API for managing users', contact: { name: 'API Support', email: 'support@example.com', }, license: { name: 'MIT', }, }, servers: [ { url: 'https://api.example.com', description: 'Production', }, { url: 'http://localhost:3000', description: 'Development', }, ], tags: [ { name: 'Users', description: 'User management operations', }, ], components: { securitySchemes: { bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT', description: 'JWT token for authentication', }, }, }, }, { addRoute: true, routeName: '/openapi.json', }, ); ``` -------------------------------- ### Handling Error Responses (404 Not Found) Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/typed-response.md Demonstrates how to return different response types, including error responses like 404 Not Found, based on request parameters. ```typescript app.get( '/users/:id', openApi({ responses: { 200: z.object({ id: z.string(), name: z.string() }), 404: z.object({ error: z.string() }), }, request: { param: z.object({ id: z.string() }), }, }), (c) => { const { id } = c.req.valid('param'); if (id === 'unknown') { return c.var.res(404, { error: 'User not found' }); } return c.var.res(200, { id, name: 'John Doe' }); }, ); ``` -------------------------------- ### c.var.res() Function Signature and Usage Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/typed-response.md Demonstrates the various ways to use the `res` helper function for building typed responses, including specifying status codes, payloads, and headers. ```APIDOC ## c.var.res() ### Description The `res` helper function, available as `c.var.res` in route handlers, allows for type-safe response construction. It validates the payload against the declared response schemas and automatically sets the status code and content type. ### Function Signature ```typescript // With status code and payload res( status: S, payload: InferPayload, headers?: HeaderRecord, ): Response & TypedResponse, S> // Without status code (assumes 200, only if 200 is defined in responses) res( payload: z.infer, headers?: HeaderRecord, ): Response & TypedResponse, 200, 'json'> // With headers but no status code (assumes 200) res( payload: unknown, headers: HeaderRecord, ): Response & TypedResponse ``` ### Call Signatures | Signature | Parameters | Returns | Notes | | ------------------------- | ----------------------- | ------------------------------------------- | -------------------------------------------------------- | | `res(payload)` | payload only | JSON response with status 200 | Only works if 200 is defined in responses | | `res(status, payload)` | status, payload | Response with specified status | Works for any declared status code | | `res(payload, headers)` | payload, headers | JSON response 200 with headers | Detects headers by type checking; only if 200 is defined | | `res(status, payload, headers)` | status, payload, headers | Response with all specified | Most explicit form | ### Parameters #### Payload - **payload** (unknown) - Response body. Type is validated at compile-time against the response schema for the given status. #### Status - **status** (number) - HTTP status code (100-599). Must match a declared response status in the `responses` field. #### Headers - **headers** (`HeaderRecord`) - Optional HTTP response headers. Type-safe headers with special handling for Content-Type and standard response headers. ### HeaderRecord Type ```typescript type HeaderRecord = Record & { 'Content-Type'?: BaseMime; } & Partial>; ``` Supports custom headers, standard HTTP headers, and Hono's recognized `ResponseHeader` types. ### Content-Type Inference Content-Type is automatically determined based on the schema type: - `z.string()` → `text/plain` - `z.string().format('uuid')` and other string formats → `text/plain` - `z.object()`, `z.array()`, or other complex types → `application/json` - Custom content type can be specified via `mediaType` in the response definition. ### Throws/Error Handling **Runtime Errors:** - `"Invalid status code: {status}. Must be a valid HTTP status code."`: If the passed status code is not within the valid HTTP range (100-599). - `"Response schema for status {status} not defined in OpenAPI operation."`: If the specified status code is not declared in the operation's `responses` field. **TypeScript Compile-time Errors:** - Payload shape does not match the response schema for the given status. - Status code is not declared in the operation's `responses`. - Required payload properties are missing. ``` -------------------------------- ### Response with Headers (Shorthand) Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Demonstrates adding custom response headers using the shorthand call signature of `c.var.res`. ```typescript c.var.res({ name: 'John' }, { 'x-custom': 'value' }); ``` -------------------------------- ### createOpenApiMiddleware Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/api-reference.md Used internally to create the `openApi` instance. This function can be utilized if custom error handling is required at the middleware level. ```APIDOC ## `createOpenApiMiddleware` ### Description Creates the `openApi` middleware instance. This function is primarily for internal use but can be exposed for advanced scenarios requiring custom error handling within the middleware. ### Usage ```ts function createOpenApiMiddleware(zodValidator: ZodValidatorFn = zValidator): HonoOpenApiMiddleware; ``` ### Parameters * **zodValidator** (ZodValidatorFn) - Optional. The Zod validator function to use. Defaults to `zValidator`. ### Returns * **HonoOpenApiMiddleware** - The OpenAPI middleware instance. ### See Also * [Custom Error Handling](/recipes#custom-error-handling) recipe for a full example of using this for custom error handling. ``` -------------------------------- ### Disable Automatic Route Serving Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/createOpenApiDocument.md Disables the automatic serving of the OpenAPI document at GET /doc by setting 'addRoute' to false. The generated document object can then be manually served at a custom path. ```typescript const openApiDoc = createOpenApiDocument( app, { info: { title: 'My API', version: '1.0.0', }, }, { addRoute: false }, // Don't add GET /doc ); // Manually serve the document elsewhere app.get('/openapi.json', (c) => c.json(openApiDoc)); ``` -------------------------------- ### HTML Response with Custom Media Type Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Shows how to define and return an HTML response by specifying a custom `mediaType` in the OpenAPI response definition. ```typescript (openApi({ responses: { 200: { schema: z.string(), mediaType: 'text/html' }, }, }), (c) => c.var.res(200, '

Hello

')); ``` -------------------------------- ### Document Generation Settings Interface Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/configuration.md Defines settings for generating and serving the OpenAPI document, including route addition and naming. ```typescript interface DocumentRouteSettings { addRoute?: boolean; routeName?: string; } ``` -------------------------------- ### Reusable OpenAPI Components Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/README.md Shows how to define reusable schemas within the OpenAPI components section, which can then be referenced using `$ref`. ```typescript createOpenApiDocument(app, { info: { ... }, components: { schemas: { User: userSchema, Error: errorSchema, }, }, }); // Then reference: { $ref: '#/components/schemas/User' } ``` -------------------------------- ### Response with Custom Headers Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/openApi-middleware.md Demonstrates how to include custom headers in a response using the `c.var.res()` helper provided by the openApi middleware. It defines a simple string response. ```typescript app.get( '/download', openApi({ responses: { 200: z.string(), }, }), (c) => { const headers = { 'x-custom-header': 'value' }; return c.var.res(200, 'file content', headers); }, ); ``` -------------------------------- ### Response Definition with Library Notation Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/usage.md Use library notation for a simplified response definition, allowing custom descriptions, media types, and headers. ```typescript openApi({ responses: { 200: { // the only required field! Use .meta() method on the schema to add metadata schema: z.string().meta({ description: 'HTML code', examples: ['hi!'], }), // description is optional, as opposed to OpenAPI spec description: 'My description', // mediaType is optional, it's `text/plain` if schema is z.string() // otherwise it's `application/json`, in other scenarios it should be specified mediaType: 'text/html', // headers field is also optional, but you can also use Zod schema here headers: z.object({ 'x-custom': z.string() }), // ...you can also pass all the other fields you normally would here in OpenAPI spec }, }, }); ``` -------------------------------- ### Type-Safe Response Helper Function Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/errors.md Create reusable, type-safe helper functions for sending responses, improving code clarity and reducing duplication. This example handles different response types based on conditions. ```typescript const sendUserResponse = ( c: Context, user?: { id: string; name: string }, ) => { if (!user) { return c.var.res(404, { error: 'Not found' }); } return c.var.res(200, user); }; app.get( '/users/:id', openApi({ /* ... */ }), async (c) => { const { id } = c.req.valid('param'); const user = await db.users.findById(id); return sendUserResponse(c, user); }, ); ``` -------------------------------- ### Basic Typed Response Usage Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/docs/typed-responses.md Demonstrates defining OpenAPI responses and returning a typed response using `c.var.res`. Ensure your response payload matches the defined Zod schema. ```typescript import { Hono } from 'hono'; import * as z from 'zod'; import { openApi } from 'hono-zod-openapi'; const app = new Hono().get( '/user', openApi({ responses: { 200: z.object({ name: z.string() }), 201: z.object({ created: z.boolean() }), }, }), (c) => { return c.var.res(200, { name: 'John' }); }, ); ``` -------------------------------- ### createOpenApiDocument Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/createOpenApiDocument.md Generates an OpenAPI 3.1.0 document from a Hono application by scanning routes decorated with the `openApi` middleware. It can optionally serve the document at a configurable endpoint. ```APIDOC ## Function: createOpenApiDocument ### Description Generates an OpenAPI 3.1.0 document from a Hono application by scanning routes decorated with the `openApi` middleware. Optionally serves the document at a configurable endpoint. ### Signature ```typescript export function createOpenApiDocument( router: Hono, document: HonoOpenApiDocument, { addRoute = true, routeName = '/doc' }: DocumentRouteSettings = {} ): ReturnType ``` ### Parameters #### `router` - **Type**: `Hono` - **Required**: Yes - **Description**: The Hono application instance containing routes decorated with `openApi` middleware. #### `document` - **Type**: `HonoOpenApiDocument` - **Required**: Yes - **Description**: Base OpenAPI document configuration with at least an `info` property. Extends `zod-openapi`'s `ZodOpenApiObject` but without the `openapi` version field. #### `routeSettings` - **Type**: `DocumentRouteSettings` - **Required**: No - **Default**: `{ addRoute: true, routeName: '/doc' }` - **Description**: Configuration for serving the generated document. ##### `DocumentRouteSettings` Properties - **`addRoute`** (boolean) - Optional - Default: `true` - Whether to automatically add a GET route to serve the OpenAPI document. - **`routeName`** (string) - Optional - Default: `/doc` - The path where the OpenAPI document will be served (only applies if `addRoute` is true). ### `HonoOpenApiDocument` Structure The `document` parameter extends OpenAPI's base object and must include: - **`info`** (object) - Required - OpenAPI info object with title and version. - **`info.title`** (string) - Required - Title of the API. - **`info.version`** (string) - Required - Version of the API. - **`servers`** (Array) - Optional - List of servers where the API is available. - **`tags`** (Array) - Optional - Tags to organize operations by category. - **`components`** (object) - Optional - Reusable schema components. - **`securitySchemes`** (object) - Optional - Security scheme definitions. - **`paths`** (object) - Optional - Additional path definitions beyond auto-discovered routes. ### Return Type Returns the generated OpenAPI 3.1.0 document object (from `zod-openapi`'s `createDocument`). This object includes: - `openapi`: "3.1.0" (automatically set) - `info`: The provided document info - `paths`: Auto-discovered routes merged with any provided paths - All other properties from the input document. ### Throws No errors are thrown by this function. Invalid routes (those without the `openApi` middleware) are silently skipped. ``` -------------------------------- ### Get HTTP Status Code Descriptions Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/utility-functions.md Access the `statusCodes` record to retrieve English descriptions for HTTP status codes, including wildcard patterns like '2XX'. This is useful for automatically generating response descriptions. ```typescript import { statusCodes } from 'hono-zod-openapi'; const description = statusCodes[200]; // "200 OK" const error = statusCodes[404]; // "404 Not Found" const wildcard = statusCodes['2XX']; // "2XX Success" const defaultStatus = statusCodes.default; // "Default" // Get description automatically when normalizing responses const response = { description: statusCodes[200], content: { /* ... */ } }; ``` -------------------------------- ### Response with explicit status code Source: https://github.com/paolostyle/hono-zod-openapi/blob/master/_autodocs/api-reference/typed-response.md Illustrates a POST endpoint for creating a user, explicitly returning a 201 Created status code along with the new user's ID. ```APIDOC ## POST /users ### Description Handles a POST request to create a new user, returning a 201 status code and the ID of the newly created user. ### Method POST ### Endpoint /users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the user to create. ### Response #### Success Response (201) - **id** (string) - The ID of the newly created user. #### Response Example ```json { "id": "new-id" } ``` ```