Skip to content

Hono OpenAPI

hono-openapi 是一个中间件,它通过与 Zod、Valibot、ArkType 和 TypeBox 等验证库以及所有支持 标准模式 的库集成,为你的 Hono API 自动生成 OpenAPI 文档。

¥hono-openapi is a middleware which enables automatic OpenAPI documentation generation for your Hono API by integrating with validation libraries like Zod, Valibot, ArkType, and TypeBox and all libs supporting Standard Schema.

🛠️ 安装

¥🛠️ Installation

安装该软件包以及你首选的验证库及其依赖:

¥Install the package along with your preferred validation library and its dependencies:

bash
npm install hono-openapi @hono/standard-validator

🚀 入门

¥🚀 Getting Started

1. 定义你的模式

¥ Define Your Schemas

使用你首选的验证库定义请求和响应模式。以下是使用 Valibot 的示例:

¥Define your request and response schemas using your preferred validation library. Here's an example using Valibot:

ts
import * as v from 'valibot'

const querySchema = v.object({
  name: v.optional(v.string()),
})

const responseSchema = v.string()

2. 创建路由

¥ Create Routes

使用 describeRoute 进行路由文档化和验证:

¥Use describeRoute for route documentation and validation:

ts
import { Hono } from 'hono'
import { describeRoute, resolver, validator } from 'hono-openapi'

const app = new Hono()

app.get(
  '/',
  describeRoute({
    description: 'Say hello to the user',
    responses: {
      200: {
        description: 'Successful response',
        content: {
          'text/plain': { schema: resolver(responseSchema) },
        },
      },
    },
  }),
  validator('query', querySchema),
  (c) => {
    const query = c.req.valid('query')
    return c.text(`Hello ${query?.name ?? 'Hono'}!`)
  }
)

注意:从 hono-openapi 使用 validator() 时,为 queryjsonparamform 添加的任何验证都会自动包含在 OpenAPI 请求架构中。无需在 describeRoute() 中手动定义请求参数。

¥Note:\ When using validator() from hono-openapi, any validation added for query, json, param or form is automatically included in the OpenAPI request schema.\ There’s no need to manually define request parameters inside describeRoute().


3. 生成 OpenAPI 规范

¥ Generate OpenAPI Spec

为你的 OpenAPI 文档添加一个端点:

¥Add an endpoint for your OpenAPI document:

ts
import { openAPIRouteHandler } from 'hono-openapi'

app.get(
  '/openapi',
  openAPIRouteHandler(app, {
    documentation: {
      info: {
        title: 'Hono API',
        version: '1.0.0',
        description: 'Greeting API',
      },
      servers: [
        { url: 'http://localhost:3000', description: 'Local Server' },
      ],
    },
  })
)

想了解更多?请查看我们的文档。 - https://honohub.dev/docs/openapi

¥Wanna explore more, check out our docs - https://honohub.dev/docs/openapi

Hono v4.11 中文网 - 粤ICP备13048890号