npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

hono-openapi

v0.2.1

Published

OpenAPI schema generator for Hono

Downloads

5,156

Readme

📜 Hono OpenAPI

npm version npm downloads license

This can automatically generate the OpenAPI specification for the Hono API using your validation schema, which can be used to generate client libraries, documentation, and more.

Supported Validation Libraries:

[!Note] This package is still in development and your feedback is highly appreciated. If you have any suggestions or issues, please let us know by creating an issue on GitHub.

Usage

Installation

You can install the package using favorite package manager.

For Zod

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

For Valibot

pnpm add hono-openapi @hono/valibot-validator valibot @valibot/to-json-schema

For ArkType

pnpm add hono-openapi @hono/arktype-validator arktype

For TypeBox

pnpm add hono-openapi @hono/typebox-validator @sinclair/typebox"

Basic Usage

Setting up your application

First, define your schemas, here is an example using Zod:

import z from "zod";

// For extending the Zod schema with OpenAPI properties
import "zod-openapi/extend";

const querySchema = z
  .object({
    name: z.string().optional().openapi({ example: "Steven" }),
  })
  .openapi({ ref: "Query" });

const responseSchema = z.string().openapi({ example: "Hello Steven!" });

Extending the Zod schema with OpenAPI properties is optional, but it will help you generate the OpenAPI specification. You can learn more about it here - https://github.com/samchungy/zod-openapi.

[!Tip] The querySchema schema will be registered as "#/components/schemas/Query" refs in the OpenAPI document. If you want to register the schema as referenced components, use .openapi() method.

Next, create your route -

import { Hono } from "hono";
import { describeRoute } from "hono-openapi";
import { resolver, validator as zValidator } from "hono-openapi/zod";

const app = new Hono();

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

You might be wondering why are we importing validator from hono-openapi/zod instead of @hono/zod-validator and as zValidator? This is because hono-openapi provides a wrapper around the @hono/zod-validator to make it easier to use. The idea is if you are already using @hono/zod-validator to validate your schemas, you can easily switch to hono-openapi without changing much of your code.

Finally, generate the OpenAPI specification -

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

Now, you can access the OpenAPI specification by visiting http://localhost:3000/openapi, and you can use this specification to generate client libraries, documentation, and more. Some tools that I used to generate documentation are -

Scalar Example
app.get(
  "/docs",
  apiReference({
    theme: "saturn",
    spec: {
      url: "/openapi",
    },
  })
);

And that's it! You have successfully generated the OpenAPI specification for your Hono API.

Advanced Usage

Adding Security Definitions

You can add security definitions to your OpenAPI specification by using the security property in the openAPISpecs function.

app.get(
  "/openapi",
  openAPISpecs(appRouter, {
    documentation: {
      info: {
        title: "Rhinobase Cloud",
        version: "1.0.0",
        description: "API Documentation",
      },
      components: {
        securitySchemes: {
          bearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
          },
        },
      },
      security: [
        {
          bearerAuth: [],
        },
      ],
      servers: [
        {
          url: "http://localhost:3004",
          description: "Local server",
        },
      ],
    },
  })
);

Conditionaly Hiding Routes

You can conditionally hide routes from the OpenAPI specification by using the hide property in the describeRoute function.

app.get(
  "/",
  describeRoute({
    // ...
    hide: process.env.NODE_ENV === "production",
  }),
  (c) => {
    return c.text("Private Route");
  }
);

Validating Responses

[!Warning] Experimental

You can validate the responses using the validateResponse property in the describeRoute function. This will validate the response against the schema and return an error if the response is invalid.

app.get(
  "/",
  describeRoute({
    // ...
    validateResponse: process.env.NODE_ENV === "development",
  }),
  (c) => {
    return c.text("Private Route");
  }
);

Contributing

We would love to have more contributors involved!

To get started, please read our Contributing Guide.

Credits

  • The idea for this project was inspired by ElysiaJS and their amazing work on generating OpenAPI specifications.
  • This project would not have been possible without the work of Sam Chung and his Zod OpenAPI package.