OpenAPI

OpenAPI proporciona un estàndard formal per a la descripció de les API HTTP.

Introducció

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.

Entorn de treball

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

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

Validació

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

import z from 'zod'


const birdSchema = z.object({
    name: z.string()
})

Create Routes

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) => {

    }
)

Generate OpenAPI Spec

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

Scalar example:

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", })
)

TODO