### Install hono-openapi and standard-validator Source: https://honohub.dev/docs/openapi/migration Installs the necessary `hono-openapi` and `@hono/standard-validator` packages using npm. This is the first step in migrating from older Hono validation packages. ```bash npm install hono-openapi @hono/standard-validator ``` -------------------------------- ### Install Scalar for Hono API Reference Source: https://honohub.dev/docs/openapi/ui Installs the Scalar package for Hono to generate interactive API documentation. This is a prerequisite for using Scalar's documentation features. ```bash npm install @scalar/hono-api-reference ``` -------------------------------- ### Install Swagger UI for Hono Source: https://honohub.dev/docs/openapi/ui Installs the Swagger UI package for Hono to generate API documentation. This package allows for easy integration of Swagger UI into Hono applications. ```bash npm install @hono/swagger-ui ``` -------------------------------- ### Integrate Typebox Validation with Hono Router Source: https://honohub.dev/docs/openapi/typebox Integrate Typebox schemas into Hono routes using `tValidator` for request validation. This example shows how to apply the defined `querySchema` to a GET request handler. ```typescript import { Hono } from "hono"; import { tValidator } from "@hono/typebox-validator"; const app = new Hono(); app.get("/", tValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }); ``` -------------------------------- ### Generate OpenAPI Specification with hono-openapi Source: https://honohub.dev/docs/openapi/migration Illustrates how to generate an OpenAPI specification JSON file using `hono-openapi`. It configures the `openAPIRouteHandler` with basic documentation information like title, version, and description. ```typescript import { Hono } from "hono"; import { openAPIRouteHandler } from "hono-openapi"; // Other hono apps import routes from "./routes"; const main = new Hono(); main.get( "/openapi.json", openAPIRouteHandler(routes, { documentation: { info: { title: "Hono", version: "1.0.0", description: "API for greeting users", }, }, }), ); ``` -------------------------------- ### Migrate Route Definition from createRoute to Middlewares Source: https://honohub.dev/docs/openapi/migration Shows the transformation of route definition from the older `createRoute` function provided by `@hono/zod-openapi` to the new middleware-based approach using `describeRoute` and `validator` from `hono-openapi`. This simplifies route declaration and integrates validation directly. ```typescript const route = createRoute({ method: 'get', path: '/users/{id}', request: { params: ParamsSchema, }, responses: { 200: { content: { 'application/json': { schema: UserSchema, }, }, description: 'Retrieve the user', }, }, }) ``` ```typescript import { Hono } from "hono"; import { describeRoute, validator, resolver } from "hono-openapi"; const app = new Hono(); app.get( '/users/:id', describeRoute({ responses: { 200: { content: { 'application/json': { schema: resolver(UserSchema), }, }, }, }, }), validator('params', ParamsSchema), (c) => { // ... } ); ``` -------------------------------- ### Save OpenAPI Spec to YAML File Source: https://honohub.dev/docs/openapi/persisting This script generates the OpenAPI specification from a Hono application and saves it to a YAML file. It utilizes `hono-openapi` for spec generation, `js-yaml` for YAML conversion, and `fs` for file writing. This method is suitable for caching and serving specs, especially in serverless architectures. Ensure `js-yaml` is installed (`npm install js-yaml`). It may have limitations with conditionally hidden routes. ```javascript import fs from 'node:fs'; import { generateSpecs } from 'hono-openapi'; import yaml from 'js-yaml'; // Your Hono app import mainApp from "./app"; async function main() { const specs = await generateSpecs(mainApp, { // Documentation metadata }); fs.writeFileSync('./path/to/openapi.yaml', yaml.dump(specs)); } main() ``` -------------------------------- ### Update Hono Router with Valibot Validation Source: https://honohub.dev/docs/openapi/valibot Integrate Valibot validation into Hono routes using `vValidator` from `hono-openapi`. This example demonstrates how to validate query parameters. ```typescript import { Hono } from "hono"; import { vValidator } from "@hono/valibot-validator"; const app = new Hono(); app.get("/", vValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }); ``` -------------------------------- ### Include All Paths in OpenAPI Spec Source: https://honohub.dev/docs/openapi/zod This example shows how to use the `includeEmptyPaths: true` option within the `openAPIRouteHandler` configuration. This option ensures that all defined routes in the Hono app are included in the generated OpenAPI specification, which is particularly useful for debugging and testing purposes. ```typescript main.get( "/openapi.json", openAPIRouteHandler(routes, { documentation: { info: { title: "Hono", version: "1.0.0", description: "API for greeting users", }, }, includeEmptyPaths: true }), ); ``` -------------------------------- ### Update Zod Import for Hono OpenAPI Migration Source: https://honohub.dev/docs/openapi/migration Demonstrates how to change the import statement for Zod when migrating from `@hono/zod-openapi` to directly importing from `zod`. This reflects the removal of Zod integration from the `@hono/zod-openapi` package. ```typescript - import { z } from "@hono/zod-openapi"; + import { z } from "zod"; ``` -------------------------------- ### GET /openapi.json Source: https://honohub.dev/docs/openapi/effect Serves the automatically generated OpenAPI specification for the Hono application. This endpoint uses `openAPIRouteHandler` to create the spec based on defined routes. ```APIDOC ## GET /openapi.json ### Description Serves the OpenAPI specification JSON for the Hono application. This is automatically generated based on the routes defined in your application using the `openAPIRouteHandler`. ### Method GET ### Endpoint /openapi.json ### Parameters None ### Request Example None ### Response #### Success Response (200) - **openapi_spec** (object) - The OpenAPI specification in JSON format. #### Response Example ```json { "openapi": "3.0.0", "info": { "title": "Hono", "version": "1.0.0", "description": "API for greeting users" }, "paths": { "/greeting": { "get": { "summary": "Get a greeting", "responses": { "200": { "description": "A greeting message" } } } } } } ``` ### Configuration Options - `routes`: The Hono router object containing your defined routes. - `options.documentation`: An object to customize the OpenAPI documentation info. - `info.title` (string): The title of your API. - `info.version` (string): The version of your API. - `info.description` (string): A brief description of your API. - `options.includeEmptyPaths` (boolean): If true, includes all routes even if they don't have OpenAPI documentation. Useful for debugging. ``` -------------------------------- ### Save OpenAPI Spec to JSON File Source: https://honohub.dev/docs/openapi/persisting This script generates the OpenAPI specification from a Hono application and saves it to a JSON file. It uses `hono-openapi` to generate the specs and `fs` to write the file. This approach is useful for caching specs in stateful environments or serving them directly from a file in serverless setups. Note that it might not work with conditionally hidden routes. ```javascript import fs from 'node:fs'; import { generateSpecs } from 'hono-openapi'; // Your Hono app import mainApp from "./app"; async function main() { const specs = await generateSpecs(mainApp, { // Documentation metadata }); fs.writeFileSync('./path/to/openapi.json', JSON.stringify(specs, null, 2)); } main() ``` -------------------------------- ### Integrate Arktype Validator with Hono Router Source: https://honohub.dev/docs/openapi/arktype Demonstrates how to integrate Arktype validation middleware directly into a Hono router. This example shows basic usage for validating query parameters and returning a response based on the validated data. ```typescript import { Hono } from "hono"; import { arktypeValidator } from "@hono/arktype-validator"; const app = new Hono(); app.get("/", arktypeValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }); ``` -------------------------------- ### Generate OpenAPI Spec with Hono Source: https://honohub.dev/docs/openapi/typebox This code snippet demonstrates how to use `openAPIRouteHandler` to serve an OpenAPI specification at `/openapi.json`. It requires `hono` and `hono-openapi` as dependencies. The handler takes your defined routes and documentation options to generate the spec. ```typescript import { Hono } from "hono"; import { openAPIRouteHandler } from "hono-openapi"; // Other hono apps import routes from "./routes"; const main = new Hono(); main.get( "/openapi.json", openAPIRouteHandler(routes, { documentation: { info: { title: "Hono", version: "1.0.0", description: "API for greeting users", }, }, }), ); ``` -------------------------------- ### Load Vendor Libraries with Custom Schema Parsing in Hono Source: https://honohub.dev/docs/openapi/helpers Illustrates how to load vendor libraries, like Zod, with custom schema parsing logic for Hono OpenAPI. It uses `loadVendor` and demonstrates integration with Standard Schema for OpenAPI conversion. ```typescript import { z } from "zod/v4"; import { toJSONSchema } from "zod/v4/core"; import { loadVendor } from "hono-openapi" import { convertToOpenAPISchema } from "@standard-community/standard-openapi/convert"; loadVendor("zod", { toOpenAPISchema: (schema, context) => { return convertToOpenAPISchema(toJSONSchema(schema, { io: "input" }), context); }, }); ``` -------------------------------- ### Generate API Docs with Swagger UI in Hono Source: https://honohub.dev/docs/openapi/ui Integrates Swagger UI into a Hono application to serve API documentation. It requires an OpenAPI specification located at '/openapi.json' and sets up a '/docs' route for accessing the UI. ```javascript import { swaggerUI } from '@hono/swagger-ui' app.get( '/docs', swaggerUI({ url: '/openapi.json', }) ) ``` -------------------------------- ### Generate API Docs with Scalar in Hono Source: https://honohub.dev/docs/openapi/ui Integrates Scalar into a Hono application to serve interactive API documentation. It assumes an OpenAPI specification is available at '/openapi.json' and configures Scalar with a 'saturn' theme. ```javascript import { Scalar } from "@scalar/hono-api-reference"; app.get( "/docs", Scalar({ theme: "saturn", url: "/openapi.json", }) ); ``` -------------------------------- ### Hono OpenAPI Route Description with Arktype Resolver Source: https://honohub.dev/docs/openapi/arktype Shows how to update a Hono route to use `hono-openapi` for describing routes and responses, leveraging Arktype schemas with the `resolver` function. This approach integrates validation and OpenAPI documentation seamlessly. ```typescript import { Hono } from "hono"; import { validator as arktypeValidator, resolver, describeRoute, } from "hono-openapi"; const app = new Hono(); app.get( "/", describeRoute({ responses: { 200: { description: "Successful response", content: { "application/json": { schema: resolver(responseSchema), }, }, }, }, }), arktypeValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }, ); ``` -------------------------------- ### Define Schema References with Typebox Options Source: https://honohub.dev/docs/openapi/typebox Define Typebox schemas and use the `options` property to pass a reference to the schema. This is useful for reusable schemas within the OpenAPI specification. ```typescript const schema = Compile( Type.Object({ myString: Type.String(), myUnion: Type.Union([Type.Number(), Type.Boolean()]) }, { description: "My neat object schema", ref: "MyNeatObjectSchema", }), ); ``` -------------------------------- ### Integrate Hono OpenAPI with Valibot and describeRoute Source: https://honohub.dev/docs/openapi/valibot Combine Hono OpenAPI with Valibot for route descriptions and response schema validation. It uses `describeRoute` to define response specifications and `resolver` to link Valibot schemas. ```typescript import { Hono } from "hono"; import { validator as vValidator, resolver, describeRoute, } from "hono-openapi"; const app = new Hono(); app.get( "/", describeRoute({ responses: { 200: { description: "Successful response", content: { "application/json": { schema: resolver(responseSchema), }, }, }, }, }), vValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }, ); ``` -------------------------------- ### Type-Safe Responses with Hono OpenAPI `describeResponse` Source: https://honohub.dev/docs/openapi/arktype Demonstrates how to use the `describeResponse` function from `hono-openapi` to automatically infer and document response body types using Arktype schemas. This provides type safety for both the implementation and the generated OpenAPI specification. ```typescript import { Hono } from "hono"; import { describeResponse } from "hono-openapi"; import { type } from "arktype"; const app = new Hono(); const successResponseSchema = type({ message: "string", }); const errorResponseSchema = type({ error: "string", }); app.get( "/", describeResponse( (c) => { return c.json({ message: "Hello Hono!" }, 200); }, { 200: { description: "Success", content: { "application/json": { vSchema: successResponseSchema, }, }, }, 400: { description: "Error", content: { "application/json": { vSchema: errorResponseSchema, }, }, }, }, ), ); ``` -------------------------------- ### Update Router with Hono OpenAPI Middleware Source: https://honohub.dev/docs/openapi/typebox Update Hono router to use `hono-openapi` middleware for route description and validation. This includes importing `tValidator`, `resolver`, and `describeRoute` to define OpenAPI specifications. ```typescript import { Hono } from "hono"; import { validator as tValidator, resolver, describeRoute, } from "hono-openapi"; const app = new Hono(); app.get( "/", describeRoute({ responses: { 200: { description: "Successful response", content: { "application/json": { schema: resolver(responseSchema), }, }, }, }, }), tValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }, ); ``` -------------------------------- ### Configure Arktype Schemas for Global References Source: https://honohub.dev/docs/openapi/arktype Illustrates how to configure Arktype schemas to support global references by augmenting the global `ArkEnv` interface. This allows defining reusable schema components that can be referenced across different parts of the application. ```typescript // add this anywhere in your project declare global { interface ArkEnv { meta(): { // meta properties should always be optional ref?: string; }; } } const schema = type({ myString: "string", myUnion: "number | boolean", }) .describe("My neat object schema") .configure({ ref: "MyNeatObjectSchema", }); ``` -------------------------------- ### Define Effect Schema with Annotations Source: https://honohub.dev/docs/openapi/effect Shows how to define an Effect schema and use the `annotations` function to add metadata like description and identifier, which can be useful for OpenAPI generation. ```typescript import { Schema } from "effect"; const schema = Schema.standardSchemaV1( Schema.Struct({ myString: Schema.String, myUnion: Schema.Union(Schema.Number, Schema.Boolean), }).annotations({ description: "My neat object schema", identifier: "MyNeatObjectSchema", }), ); ``` -------------------------------- ### Define Zod Schema with Reference for Zod v3 Source: https://honohub.dev/docs/openapi/zod Define a Zod schema with a reference using the `.openapi({ ref: 'SchemaName' })` method, suitable for Zod v3 and the `zod-openapi` library. ```typescript import "zod-openapi/extend"; const schema = z .object({ myString: z.string(), myUnion: z.union([z.number(), z.boolean()]), }) .describe("My neat object schema").openapi({ ref: "MyNeatObjectSchema", }); ``` -------------------------------- ### Define Zod Schema with Reference for Zod v4 Source: https://honohub.dev/docs/openapi/zod Define a Zod schema with a reference using the `.meta({ ref: 'SchemaName' })` method, suitable for Zod v4 and integration with OpenAPI. ```typescript const schema = z .object({ myString: z.string(), myUnion: z.union([z.number(), z.boolean()]), }) .describe("My neat object schema").meta({ ref: "MyNeatObjectSchema", }); ``` -------------------------------- ### Add TypeSense for Response Body with describeResponse Source: https://honohub.dev/docs/openapi/typebox Use `describeResponse` from `hono-openapi` to automatically provide typesense for response bodies. This function takes a handler and an options object detailing different response scenarios with their respective schemas. ```typescript const successResponseSchema = Compile(Type.Object({ message: Type.String(), })); const errorResponseSchema = Compile(Type.Object({ error: Type.String(), })); app.get( "/", describeResponse( (c) => { return c.json({ message: "Hello Hono!" }, 200); }, { 200: { description: "Success", content: { "application/json": { vSchema: successResponseSchema, }, }, }, 400: { description: "Error", content: { "application/json": { vSchema: errorResponseSchema, }, }, }, }, ), ); ``` -------------------------------- ### Pass Schema Reference with Valibot metadata Source: https://honohub.dev/docs/openapi/valibot Use the `metadata` function in Valibot to assign a reference name to a schema. This is useful for referencing complex schemas within OpenAPI documentation. ```typescript const schema = v.pipe( v.object({ myString: v.string(), myUnion: v.union([v.number(), v.boolean()]) }), v.description("My neat object schema"), v.metadata({ ref: "MyNeatObjectSchema", }), ); ``` -------------------------------- ### Add TypeSense for Response Body with describeResponse Source: https://honohub.dev/docs/openapi/valibot Utilize `describeResponse` from `hono-openapi` to automatically generate type information for response bodies based on Valibot schemas, enabling better auto-completion and validation. ```typescript import { Hono } from "hono"; import { describeResponse } from "hono-openapi"; import * as v from "valibot"; const successResponseSchema = v.object({ message: v.string(), }); const errorResponseSchema = v.object({ error: v.string(), }); const app = new Hono(); app.get( "/", describeResponse( (c) => { return c.json({ message: "Hello Hono!" }, 200); }, { 200: { description: "Success", content: { "application/json": { vSchema: successResponseSchema, }, }, }, 400: { description: "Error", content: { "application/json": { vSchema: errorResponseSchema, }, }, }, }, ), ); ``` -------------------------------- ### Define Typebox Schemas for Hono OpenAPI Source: https://honohub.dev/docs/openapi/typebox Define validation schemas using Typebox for query parameters and response bodies. These schemas are compiled and used by hono-openapi to generate OpenAPI specifications. ```typescript import Type from "typebox"; import { Compile } from "typebox/compile"; // Validation for query parameters, eg - `/hello?name=John` const querySchema = Compile(Type.Object({ name: Type.Optional(Type.String()), })); // Validation for response body, eg - `"Hello, John!"` const responseSchema = Compile(Type.String()); ``` -------------------------------- ### Add Typesense for Response Body with Hono OpenAPI Source: https://honohub.dev/docs/openapi/zod Automatically provide typesense for response bodies in Hono OpenAPI by passing Zod schemas to the `describeResponse` function. ```typescript const successResponseSchema = z.object({ message: z.string(), }); const errorResponseSchema = z.object({ error: z.string(), }); app.get( "/", describeResponse( (c) => { return c.json({ message: "Hello Hono!" }, 200); }, { 200: { description: "Success", content: { "application/json": { vSchema: successResponseSchema, }, }, }, 400: { description: "Error", content: { "application/json": { vSchema: errorResponseSchema, }, }, }, }, ), ); ``` -------------------------------- ### Integrate Hono OpenAPI with Zod Validator Source: https://honohub.dev/docs/openapi/zod Update Hono router to use zValidator from hono-openapi for request validation and describeRoute for documenting routes and responses with Zod schemas. ```typescript import { Hono } from "hono"; import { validator as zValidator, resolver, describeRoute, } from "hono-openapi"; const app = new Hono(); app.get( "/", describeRoute({ responses: { 200: { description: "Successful response", content: { "application/json": { schema: resolver(responseSchema), }, }, }, }, }), zValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }, ); ``` -------------------------------- ### Conditionally Hide Hono Routes from OpenAPI Source: https://honohub.dev/docs/openapi/helpers Demonstrates how to hide routes from the OpenAPI specification using the `hide` property in `describeRoute`. This can be a boolean value or a function that receives route context, useful for environment-specific routing. ```typescript app.get( "/", describeRoute({ // ... hide: process.env.NODE_ENV === "production", }), (c) => { return c.text("Private Route"); } ); ``` ```typescript app.get( "/", describeRoute({ hide: ({ c, path, method }) => c.env.NODE_ENV === "production", }), ); ``` -------------------------------- ### Integrate Hono OpenAPI with Effect Validator Source: https://honohub.dev/docs/openapi/effect Demonstrates how to integrate Hono OpenAPI with Effect validator for request validation and response description. It shows updating the router to use hono-openapi middleware. ```typescript import { Hono } from "hono"; import { validator as effectValidator, resolver, describeRoute, describeResponse } from "hono-openapi"; import { Schema } from "effect"; const app = new Hono(); // Validation for query parameters, eg - `/hello?name=John` const querySchema = Schema.standardSchemaV1( Schema.Struct({ message: Schema.optional(Schema.String), }), ); // Validation for response body, eg - `"Hello, John!"` const responseSchema = Schema.standardSchemaV1(Schema.String); const successResponseSchema = Schema.standardSchemaV1( Schema.Struct({ message: Schema.optional(Schema.String), }), ); const errorResponseSchema = Schema.standardSchemaV1( Schema.Struct({ error: Schema.String, }), ); app.get( "/", describeRoute({ responses: { 200: { description: "Successful response", content: { "application/json": { schema: resolver(responseSchema), }, }, }, }, }), effectValidator("query", querySchema), (c) => { const query = c.req.valid("query"); return c.text(`Hello ${query?.name ?? "Hono"}!`); }, ); app.get( "/", describeResponse( (c) => { return c.json({ message: "Hello Hono!" }, 200); }, { 200: { description: "Success", content: { "application/json": { vSchema: successResponseSchema, }, }, }, 400: { description: "Error", content: { "application/json": { vSchema: errorResponseSchema, }, }, }, }, ), ); ``` -------------------------------- ### Manually Set OperationId for Hono OpenAPI Routes Source: https://honohub.dev/docs/openapi/helpers Explains how to manually set the `operationId` for a route in Hono OpenAPI using `describeRoute`. This can be a static string or a function that generates the ID based on route details. ```typescript app.get( "/", describeRoute({ operationId: "getHello", }), ); ``` ```typescript app.get( "/", describeRoute({ operationId: (route) => `${route.method}-${route.path}`, }), ); ``` -------------------------------- ### Define Valibot Schemas for Hono OpenAPI Source: https://honohub.dev/docs/openapi/valibot Define validation schemas using Valibot for query parameters and response bodies. These schemas are used by hono-openapi to generate OpenAPI specifications. ```typescript import * as v from "valibot"; // Validation for query parameters, eg - `/hello?name=John` const querySchema = v.object({ name: v.optional(v.string()), }); // Validation for response body, eg - `"Hello, John!"` const responseSchema = v.string(); ``` -------------------------------- ### Define Zod Schemas for Hono Validation Source: https://honohub.dev/docs/openapi/zod Define Zod schemas for validating query parameters and response bodies in Hono applications. These schemas are crucial for generating OpenAPI specifications. ```typescript import z from "zod"; // Or // import z from "zod/v4"; // If you are using Zod v4 // Validation for query parameters, eg - `/hello?name=John` const querySchema = z.object({ name: z.string().optional(), }); // Validation for response body, eg - `"Hello, John!"` const responseSchema = z.string(); ``` -------------------------------- ### Add JWT Bearer Authentication to OpenAPI Spec Source: https://honohub.dev/docs/openapi/security This snippet demonstrates how to define and apply JWT bearer authentication to your OpenAPI specification using HonoHub's `openAPIRouteHandler`. It configures the `securitySchemes` component and applies the `bearerAuth` scheme globally to the API. ```typescript main.get( "/openapi.json", openAPIRouteHandler(app, { documentation: { components: { securitySchemes: { bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT", }, }, }, security: [ { bearerAuth: [], }, ], servers: [ { url: "http://localhost:3000", description: "Local server", }, ], }, }) ); ``` -------------------------------- ### Define Effect Validation Schemas for Hono Source: https://honohub.dev/docs/openapi/effect Defines validation schemas using Effect for query parameters and response bodies in Hono applications. These schemas are used to generate OpenAPI specifications. ```typescript import { Schema } from "effect"; // Validation for query parameters, eg - `/hello?name=John` const querySchema = Schema.standardSchemaV1( Schema.Struct({ message: Schema.optional(Schema.String), }), ); // Validation for response body, eg - `"Hello, John!"` const responseSchema = Schema.standardSchemaV1(Schema.String); ``` -------------------------------- ### Define Arktype Validation Schemas for Hono Source: https://honohub.dev/docs/openapi/arktype Defines validation schemas using Arktype for query parameters and response bodies in Hono applications. These schemas are crucial for validating incoming request data and structuring outgoing responses, and are used by hono-openapi to generate OpenAPI specifications. ```typescript import { type } from "arktype"; // Validation for query parameters, eg - `/hello?name=John` const querySchema = type({ "name?": "string", }); // Validation for response body, eg - `"Hello, John!"` const responseSchema = type("string"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.