Skip to content

OpenAPI

OpenAPI it’s an open standard for describing your APIs, allowing you to provide an API specification encoded in a JSON or YAML document.

It provides a comprehensive dictionary of terms that reflects commonly-understood concepts in the world of APIs, embedding the fundamentals of HTTP and JSON.

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.

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

Terminal window
bun add hono-openapi @hono/zod-validator zod zod-openapi

A continuació defineix un esquema de validació pel tipus bird:

Terminal window
import z from 'zod'
const birdSchema = z.object({
name: z.string()
})

Use describeRoute for route documentation and validation:

import { describeRoute } from 'hono-openapi'
app.post('/api/bird',
describeRoute({ description: 'Add a bird', requestBody: birdSchema}),
async (c) => {
}
)

Add an endpoint for your OpenAPI document:

import { openAPISpecs } from 'hono-openapi'
app.get(
'/api/openapi',
openAPISpecs(app, {
documentation: {
info: {
title: 'Earth API',
version: '1.0.0',
description: 'Earth API',
},
servers: [
{ url: 'http://localhost:8787', description: 'Local Server' },
],
},
})
)

Now, you can access the OpenAPI specification by visiting http://localhost:8787/api/openapi

You can use this specification to generate client libraries, documentation, and more.

Scalar example:

Terminal window
bun add @scalar/hono-api-reference

Set up Zod OpenAPI Hono and pass the configured URL to the Scalar middleware:

// // Use the middleware to serve the Scalar API Reference at /scalar
app.get(
"/api",
Scalar({ url: "/api/openapi", })
)

El contingut d'aquest lloc web té llicència CC BY-NC-ND 4.0.

©2022-2025 xtec.dev