Skip to content

🔥 feat: Add OpenAPI middleware#3702

Draft
gaby wants to merge 66 commits into
mainfrom
2025-08-21-14-48-18
Draft

🔥 feat: Add OpenAPI middleware#3702
gaby wants to merge 66 commits into
mainfrom
2025-08-21-14-48-18

Conversation

@gaby
Copy link
Copy Markdown
Member

@gaby gaby commented Aug 21, 2025

Description

This PR introduces an OpenAPI middleware that auto-generates OpenAPI 3.0 specifications from registered Fiber routes. The middleware provides comprehensive support for documenting APIs through both fluent route methods and middleware configuration, making it easy to maintain up-to-date API documentation.

Changes introduced

  • OpenAPI Middleware Package: New middleware that automatically generates OpenAPI 3.0 JSON specifications from your Fiber application routes

  • Route Metadata Support: Extended the Route struct with OpenAPI-specific fields including Summary, Description, Tags, Parameters, RequestBody, Responses, Consumes, Produces, and Deprecated

  • Fluent API Methods: Added chainable methods to App, Group, and domainRouter for documenting routes inline (e.g., .Summary(), .Description(), .Tags(), .Parameter(), .Response(), .RequestBody())

  • Schema References: Support for OpenAPI schema references ($ref) and examples at the parameter, request body, and response levels

  • Auto-filtering: Automatically filters out Fiber's auto-generated HEAD routes (via Route.IsAutoHead()) and middleware routes registered with Use() (via Route.IsMiddleware()) to avoid cluttering the spec with synthetic operations

  • Route Introspection Methods: Added IsMiddleware() and IsAutoHead() public methods on Route to allow middleware and external consumers to distinguish middleware/auto-generated routes from user-defined routes

  • Flexible Configuration: Per-route metadata can be provided via fluent API or global middleware config (keyed by Fiber route syntax, e.g. GET /users/:id), with config taking precedence

  • Explicit Request Body Suppression: A non-nil config RequestBody with an empty Content map is treated as an explicit "no request body" override, preventing the default auto-insertion for POST/PUT/PATCH methods

  • Group Support: Correctly handles grouped routes and mounted sub-apps with proper path resolution

  • Domain Router Support: All OpenAPI fluent methods are implemented on domainRouter, ensuring domain-scoped routes can be documented identically to standard routes

  • Safe Route Cloning: copyRoute() deep-clones all OpenAPI-related fields including Tags, Parameters, Responses, and RequestBody to prevent shared backing arrays between mounted/cloned apps

  • Immutable Route Metadata: App.Tags() defensive-copies the incoming variadic slice before storing, preventing caller-side mutations from affecting route metadata

  • OpenAPI Spec Validity: buildRequestBody() omits the request body entirely when content is empty, preventing invalid OpenAPI documents with "content":null

  • Merge Conflict Fixes: Resolved duplicate field declarations in Route struct, handler type conversion issues, semantic conflicts in test files, and integrated parallel benchmark tests from main branch

  • Code Quality Improvements: Fixed all lint issues (deprecated utils.ToLower replaced with utilsstrings.ToLower, 28 httpNoBody warnings, 5 whyNoLint warnings, 4 paramTypeCombine warnings, 2 hugeParam warnings), applied struct alignment optimizations (reduced Operation struct from 136 to 128 bytes, Media struct from 48 to 40 bytes), and ensured code passes all quality checks with 0 issues

  • Security Hardening:

    • Input Validation: Consumes() and Produces() now trim whitespace before validation, preventing unexpected panics from inputs like " application/json" or trailing spaces
    • OpenAPI Path Template Generation: Implemented convertToOpenAPIPath() function that properly converts Fiber route patterns to valid OpenAPI path templates by stripping type constraints (:id<int>{id}), handling regex constraints, converting wildcards (* and +{wildcard}), and skipping optional markers (?)
    • Nil Pointer Protection: Added defensive nil check in appendOrReplaceParameter() to prevent potential runtime panics if code is refactored
    • Bounds Checking: All array/string indexing operations in convertToOpenAPIPath() properly guarded with length checks to prevent index out of bounds errors
    • Comprehensive Testing: Added 9 test cases covering simple paths, parameters with constraints, regex constraints, optional parameters, wildcards, plus params, multiple parameters, and various delimiters
  • Documentation Improvements:

    • Caching Behavior: Added explicit documentation explaining that the OpenAPI spec is generated once on the first matching request and cached for the process lifetime, warning users to register the middleware after all routes
    • Markdown Compliance: All documentation properly formatted and passing markdown linting with 0 errors
  • Test Coverage Improvements: Comprehensive test suite with 93.1% code coverage (exceeding 90% goal)

    • Added 10 new test functions covering request body merge scenarios, media content defaults, path resolution edge cases, parameter merging, schema handling, HTTP method logic, nil parameter handling, marshal errors, and empty media types
    • All tests use t.Parallel() for concurrent execution
    • Per-function coverage improvements: mergeConfigParameters (76.9% → 92.3%), buildRequestBody (58.8% → 94.1%), schemaFrom (70.0% → 90.0%), shouldIncludeRequestBody (77.8% → 88.9%), resolvedSpecPath (70.6% → 82.4%), convertMediaContent (63.2% → 78.9%)
  • Benchmarks: No performance impact as spec generation happens once on first request via sync.Once. Merged 17 parallel benchmark tests from main branch to ensure thread-safety of router operations.

  • Documentation Update: Added comprehensive documentation at docs/middleware/openapi.md with examples and configuration options. Operations key format clarified to use Fiber route syntax (e.g. GET /users/:id). Added explicit caching behavior warnings. All markdown properly formatted and passing linting.

  • Changelog/What's New: OpenAPI middleware enables automatic API documentation generation from route definitions. Default responses documented as 200 OK for most methods, 204 No Content for DELETE and HEAD. Properly handles Fiber route constraints and wildcards in generated OpenAPI paths.

  • Migration Guide: No migration needed - this is a new opt-in middleware

  • API Alignment with Express: Not applicable - OpenAPI specification is framework-agnostic

  • API Longevity: The middleware uses OpenAPI 3.0 standard with extensible configuration structures to accommodate future enhancements. Security hardening ensures production stability.

  • Examples: Documentation includes examples for basic usage, custom metadata, schema references, grouped routes, and proper middleware registration order

Type of change

  • New feature (non-breaking change which adds functionality)
  • Code consistency (non-breaking change which improves code reliability and robustness)
  • Performance improvement (non-breaking change which improves efficiency)

Checklist

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.
  • Completed comprehensive security audit to prevent runtime panics and ensure production stability.
  • Achieved 93.1% test coverage with comprehensive test suite covering all edge cases.

📍 Connect Copilot coding agent with Jira, Azure Boards or Linear to delegate work to Copilot in one click without leaving your project management tool.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Aug 21, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b15d4aa7-86fd-4650-ab49-04dfee728309

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 2025-08-21-14-48-18

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gaby gaby changed the title feat: add openapi middleware 🔥 feat: Add OpenAPI middleware Aug 21, 2025
@gaby gaby added the v3 label Aug 21, 2025
@gaby gaby added this to v3 Aug 21, 2025
@gaby gaby added this to the v3 milestone Aug 21, 2025
@codecov
Copy link
Copy Markdown

codecov Bot commented Aug 21, 2025

Codecov Report

❌ Patch coverage is 85.37095% with 140 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.91%. Comparing base (395154e) to head (d20ab51).

Files with missing lines Patch % Lines
middleware/openapi/openapi.go 85.61% 32 Missing and 29 partials ⚠️
router.go 64.65% 39 Missing and 2 partials ⚠️
app.go 87.30% 15 Missing and 10 partials ⚠️
middleware/openapi/schema.go 88.79% 8 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3702      +/-   ##
==========================================
- Coverage   91.37%   90.91%   -0.46%     
==========================================
  Files         132      135       +3     
  Lines       13161    14106     +945     
==========================================
+ Hits        12026    12825     +799     
- Misses        719      818      +99     
- Partials      416      463      +47     
Flag Coverage Δ
unittests 90.91% <85.37%> (-0.46%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gaby gaby moved this to In Progress in v3 Aug 21, 2025
@gaby
Copy link
Copy Markdown
Member Author

gaby commented Aug 21, 2025

/gemini review

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@gaby
Copy link
Copy Markdown
Member Author

gaby commented Aug 21, 2025

/gemini review

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new OpenAPI middleware for auto-generating API specifications. The implementation is solid, with good test coverage and documentation. I've identified a potential improvement to prevent the middleware from documenting its own endpoint in the generated spec, which would make the output cleaner for API consumers. I also found a minor formatting issue in the documentation. Overall, this is a great feature addition.

Comment thread docs/middleware/openapi.md Outdated
Comment thread middleware/openapi/openapi.go Outdated
@ReneWerner87
Copy link
Copy Markdown
Member

nice feature, thx @gaby
can you update and convert the DRAFT to READY (when it is ready for you)

@gaby gaby requested a review from Copilot October 25, 2025 16:44
@gaby
Copy link
Copy Markdown
Member Author

gaby commented Oct 25, 2025

/gemini review

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces an OpenAPI middleware that auto-generates OpenAPI 3.0 specifications from registered Fiber routes. The implementation adds per-route metadata capabilities (summary, description, tags, parameters, request/response bodies, deprecation) that can be configured either through fluent route builders or global middleware configuration.

Key changes:

  • New OpenAPI middleware package with spec generation and JSON serving
  • Extended Route struct with OpenAPI-specific metadata fields
  • Added fluent API methods to both App and Group for route documentation

Reviewed Changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.

Show a summary per file
File Description
middleware/openapi/openapi.go Core middleware implementation generating OpenAPI spec from routes
middleware/openapi/config.go Configuration types for middleware and operation metadata
middleware/openapi/openapi_test.go Comprehensive test suite covering spec generation scenarios
middleware/openapi/testdata/openapi.json Golden file fixture for JSON output validation
router.go Extended Route struct with OpenAPI fields and helper types
router_test.go Tests for new route metadata methods
app.go Fluent API methods for documenting routes
group.go Group delegation methods for route documentation
group_test.go Tests for group-level route documentation
docs/middleware/openapi.md User-facing middleware documentation
docs/whats_new.md Release notes entry

@gaby
Copy link
Copy Markdown
Member Author

gaby commented Oct 25, 2025

@codex review and suggest feature improvements.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new OpenAPI middleware to auto-generate API specifications from routes. The implementation is comprehensive, adding new methods to App and Group for route-level documentation, and providing configuration options for global overrides. The code is well-structured and includes extensive tests.

I have two main points of feedback. The most critical one is that the current implementation incorrectly includes middleware routes (from app.Use) in the generated OpenAPI spec, which should be fixed to ensure a clean and accurate API definition. The other is a minor improvement to an error message for better debugging. Overall, this is a great feature addition.

Comment thread middleware/openapi/openapi.go
Comment thread router.go Outdated
Comment thread app.go Outdated
Copy link
Copy Markdown
Contributor

Copilot AI commented May 17, 2026

@copilot apply changes based on the comments in this thread

Already applied in 3de46b2.

I rechecked the remaining thread items: openapi.Config now documents that config only controls top-level document metadata, copyAnyMap now deep-copies nested composite values for cloned route metadata, and docs/whats_new.md already includes the OpenAPI entry in the middleware list. I also re-ran the targeted OpenAPI/deep-copy regressions and they still pass.

Screenshot: N/A (no UI changes).

Copilot finished work on behalf of gaby May 17, 2026 16:52
@gaby
Copy link
Copy Markdown
Member Author

gaby commented May 18, 2026

@copilot Integrate the following template into the openapi middleware.

  • The URL to the cdn resources should be configurable.

Template:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>{{ .Title }} - Swagger UI</title>
    <link
      rel="stylesheet"
      href="https://unpkg.com/swagger-ui-dist@5.32.6/swagger-ui.css"
    />
  </head>
  <body>
    <div id="swagger-ui"></div>

    <script
      src="https://unpkg.com/swagger-ui-dist@5.32.6/swagger-ui-bundle.js"
      crossorigin="anonymous"
    ></script>

    <script>
      window.addEventListener("load", function () {
        const options = {{ .SwaggerOptionsJSON }};

        window.ui = SwaggerUIBundle({
          url: "{{ .OpenAPIURL }}",
          dom_id: "#swagger-ui",
          presets: [SwaggerUIBundle.presets.apis],
          persistAuthorization: true,
          ...options,
        });
      });
    </script>
  </body>
</html>

Copilot AI and others added 2 commits May 18, 2026 22:13
Copy link
Copy Markdown
Contributor

Copilot AI commented May 18, 2026

@copilot Integrate the following template into the openapi middleware.

  • The URL to the cdn resources should be configurable.

...

Implemented in 9467c40.

The OpenAPI middleware now also serves a Swagger UI page using the requested template shape, keeps the spec endpoint separate, and lets you configure the CDN asset URLs through SwaggerCSSURL and SwaggerBundleURL (with additional SwaggerOptions support for the injected Swagger UI config). I also added regression coverage for the default UI page, custom asset URLs/options, and grouped routes.

Screenshot: N/A (no UI changes rendered in this environment).

Copilot finished work on behalf of gaby May 18, 2026 22:20
@gaby
Copy link
Copy Markdown
Member Author

gaby commented May 18, 2026

@copilot

  • fix modernize failing linter
  • default uipath should be /swagger

Copy link
Copy Markdown
Contributor

Copilot AI commented May 18, 2026

@copilot

  • fix modernize failing linter
  • default uipath should be /swagger

Applied in aef8f64.

UIPath now defaults to /swagger, and I pinned the modernize runner to gopls modernize v0.21.1 in both the Makefile and CI workflow so it stays compatible with the repo’s Go 1.25 toolchain. I also updated the Swagger UI tests and middleware docs to match the new default path.

Screenshot: N/A (no UI changes rendered in this environment).

Copilot finished work on behalf of gaby May 18, 2026 22:47
@gaby
Copy link
Copy Markdown
Member Author

gaby commented May 22, 2026

@copilot audit the implementation of this middleware. The end goal is for users to be able to automatically get an openapi.json and swagger page. Similar to how frameworks like FastAPI offer.

…clusivity per OpenAPI spec

Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/15c9fc8c-eb8e-4dd2-a0f5-cb6a56c6c9c3

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

Copilot AI commented May 22, 2026

@copilot audit the implementation of this middleware. The end goal is for users to be able to automatically get an openapi.json and swagger page. Similar to how frameworks like FastAPI...

Audit completed and fixes applied in 53629ed. Key findings and fixes:

Fixed:

  • example/examples mutual exclusivity: OpenAPI spec requires these to be mutually exclusive. When both are provided, examples now takes precedence and example is omitted. Applied to both contentEntry (responses/request bodies) and mergeRouteParameters (parameters).
  • Added Components config field: $ref references (e.g. #/components/schemas/User) now resolve correctly by providing schema definitions through Config.Components. Previously these references were emitted but had no corresponding definitions in the spec.
  • Documentation accuracy: Updated docs to reflect Components usage, the example/examples precedence rule, and the RequestBody panic behavior.

Audit notes (not bugs, architectural scope for future):

  • Group-mounted middleware generates a full-app spec (not group-scoped) — documented as-is
  • Parameterized group prefixes (e.g. /tenants/:id) won't match the docs endpoints — edge case noted
  • No automatic schema/model inference from Go structs (FastAPI-level auto-generation) — would require reflection-based schema generation, significant future work
  • Swagger UI is functional with configurable CDN URLs and options

All checks pass: lint (0 issues), modernize, format, markdown, full test suite, CodeQL (0 alerts). Coverage at 90.9%.

Copilot finished work on behalf of gaby May 22, 2026 14:12
@gaby
Copy link
Copy Markdown
Member Author

gaby commented May 22, 2026

@copilot Implement automatic schema/model inference from Go structs, similar to FastAPI's auto-generation capabilities.

… inference

Add SchemaOf() function that generates OpenAPI JSON Schema from Go structs
using reflection. Supports all primitive types, nested structs, embedded
structs, slices, maps, time.Time, pointers, and custom openapi struct tags
for description, example, format, and enum values.

Includes 19 schema tests and 1 integration test. All lint checks pass.

Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/50af7681-fa58-4657-8390-570ea9fa0316

Co-authored-by: gaby <835733+gaby@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

Copilot AI commented May 22, 2026

@copilot Implement automatic schema/model inference from Go structs, similar to FastAPI's auto-generation capabilities.

Implemented in 00b3b46. Added SchemaOf() function that uses reflection to automatically generate OpenAPI JSON Schema from Go structs. Supports:

  • All Go primitive types (string, bool, int*, uint*, float*)
  • time.Time{"type": "string", "format": "date-time"}
  • Nested structs, embedded structs (flattened), slices, arrays, maps
  • Pointer fields (not included in required)
  • json tags for naming, skipping (-), and optionality (omitempty)
  • openapi struct tags for description, example, format, and enum

Usage:

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email" openapi:"format:email"`
}

// In route helpers
app.Post("/users", handler).
    RequestBodyWithExample("Create user", true, openapi.SchemaOf(User{}), "", nil, nil, fiber.MIMEApplicationJSON)

// Or in Components for $ref reuse
app.Use(openapi.New(openapi.Config{
    Components: map[string]any{
        "schemas": map[string]any{"User": openapi.SchemaOf(User{})},
    },
}))

19 schema unit tests + 1 integration test added. All quality checks pass (lint, format, modernize, betteralign, markdown, full test suite, CodeQL).

@copilot audit the implementation of this middleware. The end goal is for users to be able to automatically get an openapi.json and swagger page. Similar to how frameworks like FastAPI...

Audit completed and fixes applied in 53629ed, with schema inference added in 00b3b46.

Audit findings and fixes:

  • Fixed example/examples mutual exclusivity per OpenAPI spec (examples takes precedence)
  • Added Components config field so $ref references resolve correctly
  • Updated documentation to accurately reflect behavior

Schema inference (new in 00b3b46):

  • Added SchemaOf() for automatic Go struct → OpenAPI schema generation via reflection
  • Supports primitives, nested/embedded structs, slices, maps, time.Time, pointers
  • Custom openapi struct tags for description, example, format, enum

All checks pass: lint (0 issues), format, modernize, betteralign, markdown (0 errors), full test suite, CodeQL (0 alerts).

Copilot finished work on behalf of gaby May 22, 2026 14:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

5 participants