
Summary
Key points of this document
- Handwritten API specifications become outdated faster than the implementation.
- The goal is not to increase the number of Swaggers, but to reduce specification drift.
- Distributed generation and merging will be the basic configuration.
Overview
When API specifications are meticulously crafted by hand, the initial documentation looks good. However, if the specifications are not continuously updated with the same precision every time the implementation changes, the documentation quickly becomes outdated. In configurations with multiple backends, this discrepancy can mislead not only API consumers but also the developers themselves.
Handwritten API specifications become outdated faster than the implementation.
OpenAPI is a convenient common language for both API consumers and implementers. It allows endpoints, inputs, responses, authentication, and errors to be read as a single specification, serving as a foundation for frontend implementation, external integration, test design, and operational verification.
However, managing OpenAPI manually leads to dual maintenance of implementation and specification. For example, input validation is done with schemas like Zod in the implementation, while OpenAPI schemas are written by hand in a separate file. This might work in the short term, but every change requires reflecting the same meaning in two places. If only one is updated, the specification becomes an outdated document that only appears correct.
Especially in configurations with multiple Hono backends or domain-specific APIs, it becomes difficult to grasp which service owns which API. Even with individual Swagger UIs, overall search, tag unification, schema conflicts, and authentication method visibility are separate issues. This article organizes a design to automatically generate OpenAPI from close to the implementation and aggregate it into a unified view.
The goal is not to increase the number of Swaggers, but to reduce specification drift.
Discussions about API documentation often revolve around "wanting to produce a user-friendly Swagger." However, the fundamental problem is not the display screen. It's the discrepancy between implementation and specification, the failure to notice these discrepancies, and the progression of development and verification based on incorrect specifications.
To address this problem, specifications need to be brought closer to the implementation. Zod schemas used for input validation, route definitions, authentication boundaries, and representative response forms should be described as close to the implementation as possible. Instead of creating a huge handwritten file specifically for OpenAPI, specifications are grown as metadata for each route.
Another goal is to not lose sight of the overall picture. While splitting services clarifies responsibilities, it reduces the discoverability of APIs from the user's perspective. Therefore, each service generates only its own specification, and the integrated view is created in a separate aggregation layer. This allows for both service boundaries and discoverability.
- The correctness of the specification is maintained by updating it with the same change cycle as the implementation.
- Each backend is responsible
GET /openapi.jsononly for its own. - The integrated view should only retrieve and bundle each spec, without holding business logic or authentication processing.
- Provide API consumers with a searchable single reference, and leave service-level debugging pathways for implementers.
Distributed generation and merging will be the basic configuration.
The basic configuration is simple. Each Hono backend generates its ownopenAPIRouteHandlerin/openapi.json. While individual/docscan be provided for verification, the integrated reference that people view daily is provided by a separate service or route.
The aggregation layer obtains each/openapi.json based on the service list and merges them as an OpenAPI 3.1 document. It integrates paths, adds metadata indicating the origin to operations, and prefixes service names to components.schemas to avoid conflicts. Authentication method definitions are standardized to minimize differences between services.
With this design, no specific gateway needs to hold the specifications for all services. The aggregation layer only reads the specifications and does not proxy actual APIs or make authentication decisions. When adding a service, a/openapi.json is set up on the service side, and one line is added to the list of aggregation targets. Keeping operational units this small makes horizontal scaling easier.
Existing routes will be migrated by appending metadata.
If existing APIs are present, completely rewriting route definitions for OpenAPI compatibility is risky. Even slight changes in input validation, error bodies,c.req.valid() usage, or test expectations can alter API behavior.
Therefore, an approach wherehono-openapi'sdescribeRoute is appended as metadata is easier to manage. Place summary, tags, and responses near the route, and preserve existingzValidator validation middleware. The order is to add specification descriptions rather than changing validation implementations for OpenAPI.
There are also some points to note. For example, if you write the request body schema with the same approach as resolvers for responses, it can lead to type or runtime issues. Instead of bending the API implementation to suit the library's convenience, it's also necessary to decide to supplement the input's meaning with a summary or description, while preserving the implementation's behavior.
describeRouteshould be treated as specification metadata placed close to the implementation.- Do not forcibly replace existing input validation unless behavior changes.
- Exclude routes like CORS preflights, health checks, and internal utilities from the specification.
- Since spec generation results may be cached, the verification process should include whether a backend restart or rebuild is required.
Visualize unannotated routes and start with an inventory.
There's no need to move all routes to a clean OpenAPI at once. In fact, aiming for a complete schema immediately often halts migration. The initial goal is to visualize which paths and methods exist in which services.
Using inventory settings like includeEmptyPaths allows you to list routes even before annotation. Even with an empty schema, just seeing the path and method is a big step forward. From there, count operations without summary or tags and proceed with annotations from high-priority domains.
This inventory also serves as an implementation design review. You'll find similarly named endpoints, cross-domain duplications, APIs with ambiguous authentication boundaries, and old, unused APIs. OpenAPI compliance is not just about documentation maintenance; it's also about inventory management for API design.
When integrating, explicitly state conflicts and origins.
Simply combining the specs of multiple services will lead to name collisions in components.schemas. For example, it's natural for multiple services to have schema names like User or ErrorResponse. If mixed as is, it becomes unclear which User is being referenced.
In the aggregation layer, we namespace schema names by service and also rewrite $ref. If paths collide, a warning is issued, and it's explicitly stated which service's definition was adopted. Operations are given extended information, such as x-service, to allow tracing their origin from the integrated view.
Swagger UI can be used for the UI, but for integrated use cases involving searching and browsing multiple services, an API reference UI like Scalar is also an option. What's important is not the type of UI, but configuring it so that the browser does not directly fetch from each service. By serving the aggregated spec from the same origin, you can avoid introducing CORS and authentication complexities into the UI.
API specifications are useful, but if their scope of disclosure is mishandled, it can lead to information exposure.
OpenAPI includes information useful to attackers, such as paths, methods, input fields, responses, and authentication schemes. While this information is acceptable for public APIs, it should not be unconditionally exposed for admin panel APIs or internal processing APIs.
In a production environment, decisions must be made, such as requiring administrator privileges to view integrated documentation, separating docs for public and admin APIs, or keeping internal service specs only as CI artifacts. Maintaining OpenAPI is one thing; exposing all API structures to the internet is another.
It's also important not to write too much internal detail in the description. Operational notes, ticket numbers, internal URLs, incident history, and customer-specific business vocabulary are safer to omit from OpenAPI descriptions. The standard is to write at an abstraction level suitable for public disclosure, just like any technical document.
In CI, we confirm that generation is possible and that no new omissions occur.
OpenAPI auto-generation is not a one-time setup. We continuously check if new routes appear in the spec, if the number of operations without summaries or tags is increasing, and if component references are broken.
In CI, each service's spec is output as a file, and the aggregation process is executed. It can be more stable to validate as a build artifact rather than depending on running services over the network. Treat aggregation warnings as tests to avoid overlooking path collisions or broken schema references.
Rushing for completeness too quickly will halt the migration. Initially, the passing criteria should be that /openapi.json can be generated, all paths are inventoried, and the integrated view is not broken. After that, summaries, tags, responses, authentication methods, and representative schemas will be added, starting with the main APIs.
- Generation check: Each service's
/openapi.jsonis output as syntactically correct OpenAPI. - Aggregation check: Treat schema name collisions,
$refbreaks, and path collisions as warnings. - Omission check: Continuously monitor the number of operations without summaries or tags.
- Regression check: Confirm that input validation, error bodies, and status codes in existing tests have not changed due to OpenAPI integration.
There are limits to automatic generation.
Automatic generation is a mechanism that brings what can be understood from the implementation closer to the specification. Conversely, this means that business meanings not discernible from the implementation alone, user-facing explanations for errors, change compatibility, rate limits, and operational considerations must be written by humans.
Additionally, metadata will increase in the root file to support OpenAPI. To maintain readability, it's necessary to decide on tag naming, the granularity of response descriptions, and the location for common schemas. Trying to write everything strictly will slow down implementation, while being too coarse will render the document unusable.
A realistic standard is to write in detail about the parts that users are most likely to implement incorrectly. Is authentication required? What are the mandatory input fields? What is the typical successful response? What are the status codes for errors? Just aligning these points alone will significantly reduce the perception gap between API consumers and implementers.
OpenAPI is a continuous design asset that connects implementation and operation.
If OpenAPI is treated as a manually written artifact, it tends to become an outdated specification. By adding metadata close to the implementation, having each backend generate its own spec, and having an aggregation layer consolidate everything, the specification is maintained close to implementation changes.
What's important is not to create a perfect schema from the start. First, inventory all routes, add annotations to key APIs, and verify generation and aggregation with CI. Changing the specification from a one-time task to an operation that keeps up with daily changes will make API documentation usable for a long time.


