DEV Community

Cover image for Introducing Hono OpenAPI: Simplifying API Documentation for HonoJS
Aditya Mathur
Aditya Mathur

Posted on

Introducing Hono OpenAPI: Simplifying API Documentation for HonoJS

First things first: why create another OpenAPI library for Hono when one already exists?

This is a question many have asked. Yes, there is Zod OpenAPI, created by Yusuke. While it’s a great package, it has some significant limitations that led to the creation of a new solution.

The Challenges with @hono/zod-openapi

Let’s break down why hono-openapi was built by comparing the two approaches.

1. Syntax and Workflow Differences

Here’s an example using @hono/zod-openapi:

// Using @hono/zod-openapi 
import { OpenAPIHono, createRoute, z } from '@hono/zod-openapi';

const ParamsSchema = z.object({
  id: z
    .string()
    .min(3)
    .openapi({
      param: {
        name: 'id',
        in: 'path',
      },
      example: '1212121',
    }),
});

const route = createRoute({
  method: 'get',
  path: '/users/{id}',
  request: {
    params: ParamsSchema,
  },
});

const app = new OpenAPIHono();

app.openapi(route, (c) => {
  const { id } = c.req.valid('param');
  return c.json({ id, age: 20, name: 'Ultra-man' });
});

// The OpenAPI documentation will be available at /doc
app.doc('/doc', {
  openapi: '3.0.0',
  info: {
    version: '1.0.0',
    title: 'My API',
  },
});
Enter fullscreen mode Exit fullscreen mode

Now compare this to the same application written with hono-openapi:

// Using Hono-OpenAPI
import z from 'zod';
import { Hono } from 'hono';
import { describeRoute } from 'hono-openapi';
import { resolver, validator as zValidator } from 'hono-openapi/zod';

// Extending the Zod schema with OpenAPI properties
import 'zod-openapi/extend';

const paramSchema = z.object({
  id: z.string().min(3).openapi({ example: '1212121' }),
});

const app = new Hono();

app.get(
  '/',
  zValidator('param', paramSchema),
  (c) => {
    const param = c.req.valid('param');
    return c.text(`Hello ${param?.id}!`);
  }
);

app.get(
  '/openapi',
  openAPISpecs(app, {
    documentation: {
      info: {
        title: 'Hono',
        version: '1.0.0',
        description: 'API for greeting users',
      },
      servers: [
        { url: 'http://localhost:3000', description: 'Local server' },
      ],
    },
  })
);
Enter fullscreen mode Exit fullscreen mode

The difference is clear: hono-openapi lets you work directly within the standard HonoJS workflow. This eliminates the steep learning curve and ensures that the syntax aligns with HonoJS documentation and conventions.

2. Challenges with Opting In

With @hono/zod-openapi, retrofitting an existing HonoJS application to generate OpenAPI specs is a significant challenge. Rewriting routes for a large application can be time-consuming and error-prone. hono-openapi solves this by working as middleware, so you can add it to existing apps without major changes.

3. Limited Validator Support

The original library only supports Zod. While Zod is excellent, many developers use alternatives like Valibot, ArkType, and TypeBox. hono-openapi is validator-agnostic, offering first-class support for multiple libraries.


Why OpenAPI Specs Matter

Some might wonder, “Why bother with OpenAPI specs at all? My app works fine without them.”

Here’s why generating OpenAPI specs is a game-changer:

  1. API Client Generation: Use the specs to auto-generate clients for various programming languages, saving development time.
  2. Developer Collaboration: Keep your team in sync with up-to-date API documentation, reducing miscommunication and bugs.
  3. Streamlined Debugging: Eliminate guesswork when APIs fail by providing clear, accurate documentation for all endpoints.
  4. Best Practices: Automatically generate documentation that evolves with your codebase, ensuring consistency across branches and versions.

Here is an example of Generate Docs from OpenAPI Specs using Scalar -

Image description

And this is how you use Scalar with Hono -

import { apiReference } from '@scalar/hono-api-reference'

app.get(
  "/docs",
  apiReference({
    theme: "saturn",
    spec: {
      url: "/openapi",
    },
  })
);
Enter fullscreen mode Exit fullscreen mode

If you’ve ever worked on a team where frontend and backend developers had to manually sync API details, you’ll know how painful it can be. OpenAPI specs solve this by providing a single source of truth.


Why Choose hono-openapi?

To address these challenges and promote best practices, hono-openapi was built with the following goals in mind:

  • Validator-Agnostic: Use your preferred validation library — Zod, Typebox, ArkType, Valibot, or others.
  • Seamless Integration: Add it to any HonoJS project as middleware, with minimal changes.
  • Automatic OpenAPI Generation: Define schemas once and let the library handle the rest.
  • Type-Safe: Built with TypeScript for reliable and consistent type validation.
  • Customizable: Tailor the generated OpenAPI specs to meet your project’s requirements.

Ready to Get Started?

If this sounds like the solution you’ve been waiting for, check out the library and join the conversation:


I hope this article convinces you to try hono-openapi and see how it simplifies building and documenting APIs. Your feedback matters! Let’s build a stronger HonoJS community together.

Top comments (1)

Collapse
 
suryavirkapur profile image
Suryavir Kapur

amazing work! already switched to it :)