Skip to content

🔥 feat: Add OpenAPI middleware#3702

Draft
gaby wants to merge 31 commits intomainfrom
2025-08-21-14-48-18
Draft

🔥 feat: Add OpenAPI middleware#3702
gaby wants to merge 31 commits intomainfrom
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: 831c3a8a-62c7-4fae-a6e1-e09d7b6800b2

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 79.38144% with 140 lines in your changes missing coverage. Please review.
✅ Project coverage is 90.55%. Comparing base (c2133b7) to head (8dcfd7c).

Files with missing lines Patch % Lines
middleware/openapi/openapi.go 88.18% 21 Missing and 20 partials ⚠️
router.go 47.36% 40 Missing ⚠️
domain.go 0.00% 36 Missing ⚠️
app.go 85.80% 14 Missing and 9 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3702      +/-   ##
==========================================
- Coverage   91.22%   90.55%   -0.67%     
==========================================
  Files         123      125       +2     
  Lines       11832    12499     +667     
==========================================
+ Hits        10794    11319     +525     
- Misses        653      765     +112     
- Partials      385      415      +30     
Flag Coverage Δ
unittests 90.55% <79.38%> (-0.67%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 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.

@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 on lines +102 to +104
if r.Method == fiber.MethodConnect {
continue
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Currently, middleware routes (registered with app.Use) are included in the generated OpenAPI specification. This is not ideal as it pollutes the spec with non-endpoint routes (e.g., a logging middleware would appear as an operation for every HTTP method). These routes should be filtered out.

This can be done by checking a flag on the Route struct that indicates if it's a middleware route. Assuming the use field from fiber.Route is exported to Use (as suggested in a separate comment on router.go), you should add a check here to skip middleware routes.

if r.Method == fiber.MethodConnect || r.Use {
    continue
}

@gaby
Copy link
Copy Markdown
Member Author

gaby commented Mar 27, 2026

@copilot apply changes based on the comments in this thread

Copy link
Copy Markdown
Contributor

Copilot AI commented Mar 27, 2026

@claude[agent] there still one conflict in router_test.go

The router_test.go conflict was resolved during the merge in commit 1ecf5d1. No conflict markers remain and all tests pass.

@copilot apply changes based on the comments in this thread

Applied all 9 review comments in commits b76e04d, 9158f56, d342624:

  1. config.go + docs: Documented that Operations keys use Fiber route syntax (e.g. GET /users/:id)
  2. router.go: Tags slice now cloned in copyRoute() to prevent shared backing array
  3. openapi.go: Added IsMiddleware() and IsAutoHead() methods on Route; middleware now skips Use() routes and auto-generated HEAD routes (O(1) instead of O(n²))
  4. openapi.go: buildRequestBody() returns nil when Content is empty, preventing invalid OpenAPI documents
  5. docs/whats_new.md: Corrected default response description for DELETE/HEAD
  6. docs/middleware/openapi.md: Fixed line break in app.Use(...) rendering
  7. Added 3 new tests (middleware exclusion, empty requestBody, auto-HEAD exclusion) — 31 tests total, all passing
  8. Lint: 0 issues, format clean, markdown clean

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • exampleretry.com
    • Triggering command: /tmp/go-build1201278822/b305/client.test /tmp/go-build1201278822/b305/client.test -test.paniconexit0 -test.timeout=10m0s -test.count=1 -test.run=Test_ -c=4 -nolocalimports -importcfg /tmp/go-build545778845/b276/importcfg -pack /home/REDACTED/work/fiber/fiber/middleware/basicauth/basicauth.go /home/REDACTED/work/fiber/fiber/middleware/basicauth/config.go -p vendor/golang.org/x/crypto/inter-s W1DJhNByY 0.1-go1.25.0.linux-amd64/pkg/tool/linux_amd64/vet -I /tmp/go-build366-o (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

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

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

@gaby
Copy link
Copy Markdown
Member Author

gaby commented Mar 29, 2026

@copilot apply changes based on the comments in this thread

Copilot AI and others added 2 commits March 29, 2026 17:57
…allow explicit requestBody suppression

Agent-Logs-Url: https://github.com/gofiber/fiber/sessions/5508bb70-29bd-46df-8dc2-e44f460c9409

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

Copilot AI commented Mar 29, 2026

@copilot apply changes based on the comments in this thread

Applied in commits 49ee7a2 and 38a32b9:

  1. app.go:1040Tags() now defensive-copies the incoming slice before storing
  2. openapi.go:200-206 — Non-nil RequestBody with empty Content map is treated as explicit "no request body" override, preventing default auto-insertion for POST/PUT/PATCH
  3. CI fix — Added all 12 OpenAPI methods to domainRouter in domain.go so it satisfies the Router interface
  4. New testTest_OpenAPI_SuppressRequestBodyForPOST validates the suppression behavior

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

Copilot reviewed 12 out of 12 changed files in this pull request and generated 5 comments.

Comment on lines +825 to +845
// Consumes assigns a request media type to the most recently added route.
func (app *App) Consumes(typ string) Router {
if typ != "" {
if _, _, err := mime.ParseMediaType(typ); err != nil || !strings.Contains(typ, "/") {
panic("invalid media type: " + typ)
}
}
app.mutex.Lock()
app.latestRoute.Consumes = typ
app.mutex.Unlock()
return app
}

// Produces assigns a response media type to the most recently added route.
func (app *App) Produces(typ string) Router {
if typ != "" {
if _, _, err := mime.ParseMediaType(typ); err != nil || !strings.Contains(typ, "/") {
panic("invalid media type: " + typ)
}
}
app.mutex.Lock()
Copy link

Copilot AI Mar 30, 2026

Choose a reason for hiding this comment

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

Consumes() / Produces() validate typ without trimming whitespace, while RequestBody/Response media type handling trims and de-dupes. This makes Consumes(" application/json") (or trailing spaces) panic unexpectedly. Consider normalizing via strings.TrimSpace (or reusing the same sanitization helper used elsewhere) before validating/storing.

Copilot uses AI. Check for mistakes.
Comment on lines +93 to +102
| Property | Type | Description | Default |
|:------------|:------------------------|:----------------------------------------------------------------|:------------------:|
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
| Title | `string` | Title is the title for the generated OpenAPI specification. | `"Fiber API"` |
| Version | `string` | Version is the version for the generated OpenAPI specification. | `"1.0.0"` |
| Description | `string` | Description is the description for the generated specification. | `""` |
| ServerURL | `string` | ServerURL is the server URL used in the generated specification.| `""` |
| Path | `string` | Path is the route where the specification will be served. | `"/openapi.json"` |
| Operations | `map[string]Operation` | Per-route metadata keyed by `METHOD /path` using Fiber route syntax (e.g. `GET /users/:id`). | `nil` |

Copy link

Copilot AI Mar 30, 2026

Choose a reason for hiding this comment

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

The config table uses || at the start of each row (e.g. || Property | Type | ...), which is not valid Markdown table syntax and likely won’t render correctly. Use standard table rows starting with a single | for each line.

Copilot uses AI. Check for mistakes.
@gaby
Copy link
Copy Markdown
Member Author

gaby commented Mar 30, 2026

@claude[agent] we want to make sure the implementation is secure and stable. Fix any secure issues you find and potential things that could cause a panic during runtime of he middleware.

Note: A panic during initialization/config is fine.

@Claude
Copy link
Copy Markdown
Contributor

Claude AI commented Mar 30, 2026

@claude[agent] we want to make sure the implementation is secure and stable. Fix any secure issues you find and potential things that could cause a panic during runtime of he middleware.

Note: A pa...

Security audit completed and hardening applied in commit 9946f64:

Security Improvements:

  1. Input Validation: Consumes()/Produces() now trim whitespace before validation, preventing unexpected panics from inputs like " application/json"
  2. Path Template Generation: Fixed convertToOpenAPIPath() to properly handle Fiber route constraints and wildcards:
    • Strips type constraints: /users/:id<int>/users/{id}
    • Handles wildcards safely: /files/*/files/{wildcard}
    • Properly skips optional markers and regex constraints
  3. Nil Pointer Protection: Added defensive nil check in appendOrReplaceParameter()
  4. Bounds Checking: All array accesses in convertToOpenAPIPath() properly guarded with i < length checks
  5. Documentation: Added explicit caching behavior warning to prevent users from dynamically modifying routes after spec generation

Runtime Panic Analysis:

  • ✅ All map/slice accesses bounds-checked
  • ✅ All pointer dereferences nil-checked
  • ✅ Input sanitization with TrimSpace() for user-provided strings
  • ✅ JSON marshaling errors properly handled and wrapped
  • ✅ Route introspection handles nil routes correctly

Tests Added:

  • Comprehensive path conversion tests covering constraints, wildcards, optional params, and complex patterns

All checks pass: lint (0 issues), format, tests (all passing), markdown (0 errors).

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • exampleretry.com
    • Triggering command: /tmp/go-build1618967023/b307/client.test /tmp/go-build1618967023/b307/client.test -test.paniconexit0 -test.v=test2json -test.timeout=10m0s -test.count=1 -test.shuffle=on -trimpath ux-amd64/pkg/tool/linux_amd64/vet -p internal/trace/t-unsafeptr=false l/linux_amd64/as-unreachable=false ux-amd64/pkg/too/tmp/go-build1618967023/b102/vet.cfg --gd�� --64 3097543/b073/ ux-amd64/pkg/tool/linux_amd64/vet /tmp/cckWZZfz.s -c=4 -nolocalimports ux-amd64/pkg/too-buildtags (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

@gaby
Copy link
Copy Markdown
Member Author

gaby commented Mar 30, 2026

@claude[agent] Improve tests coverage for the openapi middleware. We want to be as close to 90% as possible.

@Claude
Copy link
Copy Markdown
Contributor

Claude AI commented Mar 30, 2026

@claude[agent] Improve tests coverage for the openapi middleware. We want to be as close to 90% as possible.

Test coverage improved from 87.5% to 93.1%, exceeding the 90% goal! 🎉

Added comprehensive tests for:

  • Request body merge scenarios and HTTP method logic
  • Media content defaults and conversion edge cases
  • Path resolution for grouped/mounted middleware
  • Parameter merging and schema handling
  • Nil/empty value edge cases

All tests pass with proper parallel execution and zero lint issues.

Commit: 8dcfd7c

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