openapi3gen

command module
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

README ΒΆ

🧬 openapi3gen

A Code-First OpenAPI 3.0 Specification Generator for Go (Gin) with Swagger UI support

openapi3gen is a lightweight, code-first tool that parses annotations in your Gin HTTP handlers and generates a complete OpenAPI 3.0 spec β€” ready to be served live or viewed in Swagger UI.


✨ Features

  • βœ… Supports OpenAPI 3.0 compliant schema
  • πŸ“Œ Generates openapi.json from handler annotations
  • πŸ” Path, query, and header param support via @Param
  • πŸ“¦ Request body model via @RequestBody
  • 🧾 Response models with $ref, @Success and @Failure
  • πŸ“€ Response headers with @Header
  • πŸ” Multiple security schemes: BearerAuth, ApiKeyAuth with custom headers
  • πŸ€– Auto-detection of parameters, request bodies, responses, and headers
  • πŸ§ͺ Auto schema generation from Go structs with openapi tags
  • 🏷 Tag-based grouping, descriptions, and @Deprecated
  • βš™οΈ CLI support: openapi3gen generate
  • 🌐 Swagger UI integration via embedded static assets

πŸ“¦ Installation

go get github.com/georgetjose/openapi3gen


πŸš€ Getting Started

Step 1: Annotate your handlers
// @Summary Get user by ID
// @Description Returns a user by ID
// @Tags user
// @Param id path string true "User ID"
// @Success 200 {object} UserResponse "Returns the user object with id and name"
// @Failure 400 {object} ErrorResponse "Invalid request payload"
// @Header 200 X-RateLimit-Remaining string true "Remaining quota"
// @Security ApiKeyAuth:X-User-Token
// @Router /user/{id} [get]
func GetUserByIDHandler(c *gin.Context) {
	id := c.Param("id")
	c.Header("X-RateLimit-Remaining", "29")
	c.JSON(200, UserResponse{ID: id, Name: "John Doe"})
	if err != nil {
		c.JSON(400, ErrorResponse{Message: err.Error()})
	}
}
Step 2: Add global metadata (optional)
// @GlobalTitle My Service API
// @GlobalVersion 1.0.0
// @GlobalDescription This is a sample API for demonstrating OpenAPI generation.
package main

Step 3: Register your models
registry := generator.NewModelRegistry()
registry.Register("UserResponse", UserResponse{})
registry.Register("ErrorResponse", ErrorResponse{})

Step 4: Generate the spec via CLI
openapi3gen generate --dir ./examples --output ./swagger/openapi.json

Step 5: Serve Swagger UI (optional)
r := gin.Default()

// Parse and generate OpenAPI spec
routes, _ := parser.ParseDirectory("./")
registry := generator.NewModelRegistry()
registry.Register("UserResponse", UserResponse{})
globalMetaData := parser.ParseGlobalMetadata("main.go")
openapi := generator.GenerateSpec(routes, registry, globalMetaData)

// Serve Swagger UI and JSON
ui.RegisterSwaggerUI(r, "")
ui.RegisterSwaggerJSONHandler(r, openapi)

Access at: http://localhost:8080/swagger


πŸ—‚οΈ Annotation Cheatsheet

Annotation Purpose Example
@GlobalTitle Title for the APIs/Service @GlobalTitle My Service API
@GlobalVersion Version of the swagger doc @GlobalVersion 1.0.0
@GlobalDescription Detailed explanation about APIs/Service @GlobalDescription This is a sample API
@Summary One-line summary @Summary Get user by ID
@Description Detailed endpoint explanation @Description Returns user data based on ID
@Tags Group endpoints @Tags user,admin
@Param Parameters in path, query, header @Param id path string true "User ID"
@RequestBody JSON body payload with struct @RequestBody {object} UserRequest true "User data"
@Success Success Response code and return object @Success 200 {object} UserResponse "Success"
@Failure Failure Response code and return object @Failure 400 {object} ErrorResponse "Bad Request"
@Header Adds response header details @Header 200 X-RateLimit string true "Rate limit"
@Security Adds authorization to endpoints @Security BearerAuth or @Security ApiKeyAuth:X-Token
@Deprecated Flags the route as deprecated in spec @Deprecated

πŸ” Security Schemes

Bearer Authentication
// @Security BearerAuth
// @Router /protected [get]
func ProtectedHandler(c *gin.Context) { ... }
API Key Authentication
// Default header (X-API-Key)
// @Security ApiKeyAuth
// @Router /api [get]

// Custom header with colon notation
// @Security ApiKeyAuth:X-User-Token
// @Router /user-auth [get]

// Custom header with bracket notation
// @Security ApiKeyAuth[x-territory-Key]
// @Router /territory [get]

πŸ€– Auto-Detection Features

openapi3gen can automatically detect many elements from your code:

  • Parameters: Detects c.Param(), c.Query(), c.GetHeader() calls
  • Request Bodies: Detects c.ShouldBindJSON() usage
  • Response Bodies: Detects c.JSON() calls with status codes
  • Response Headers: Detects c.Header() calls
Auto-Detection Example
// Minimal annotations - most things are auto-detected
// @Summary Create user auto-detect
// @Description Creates a new user with auto-detection
// @Tags user
// @Router /users/auto [post]
func CreateUserAutoHandler(c *gin.Context) {
    var req CreateUserRequest  // Auto-detected as request body
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(400, ErrorResponse{Message: err.Error()})  // Auto-detected as 400 response
        return
    }
    c.JSON(201, UserResponse{ID: "123", Name: req.Name})  // Auto-detected as 201 response
}

πŸ—οΈ Struct Schema Generation

Use openapi struct tags for enhanced schema documentation:

type CreateUserRequest struct {
    Name    string  `json:"name" openapi:"desc=Full name of the user"`
    Email   string  `json:"email" openapi:"desc=User's email address"`
    Address Address `json:"address" openapi:"desc=User's address"`
}

type Address struct {
    State   string `json:"state" openapi:"desc=State"`
    ZipCode int    `json:"zip_code" openapi:"desc=ZIP code"`
}

πŸ›  Developer Notes

Run CLI locally
go run main.go generate --dir ./examples --output ./swagger/openapi.json
Build CLI binary
go build -o openapi3gen main.go
Model Registration

Remember to register all models referenced in annotations:

registry := generator.NewModelRegistry()
registry.Register("CreateUserRequest", CreateUserRequest{})
registry.Register("UserResponse", UserResponse{})  
registry.Register("ErrorResponse", ErrorResponse{})

πŸ“Œ Roadmap

  • βœ… OpenAPI 3.0 support
  • βœ… Schema generation from Go structs
  • βœ… Swagger UI
  • βœ… CLI for static spec generation
  • βœ… Auto Detection of Path, Query & Header parameters
  • βœ… Auto Detection of Request Body
  • βœ… Auto Detection of Response Headers
  • βœ… Auto Detection of Response Body
  • βœ… Support for multiple Security schemes (BearerAuth, ApiKeyAuth)
  • βœ… Custom security headers with flexible notation
  • βœ… Enhanced struct schema generation with openapi tags
  • βœ… Nested struct support with automatic $ref generation
  • βŒ› Support enums, examples
  • βŒ› JSON/YAML output toggles
  • βŒ› Support other golang web frameworks like echo, chi etc.
  • βŒ› OpenAPI 3.1 support

🀝 Contributing

Contributions welcome!

🌟 Star the repo

πŸ› File issues and suggestions

πŸ§ͺ Add tests for new functionality

πŸ“₯ Open PRs for features or fixes


πŸ“¬ Contact

For questions, feedback, or ideas:

πŸ€– GitHub: @georgetjose

βœ‰οΈ Email: [email protected]


πŸ“„ License

openapi3gen is released under the Apache 2.0 license

Documentation ΒΆ

The Go Gopher

There is no documentation for this package.

Directories ΒΆ

Path Synopsis
examples
gin-basic command
@GlobalTitle My Service API @GlobalVersion 1.0.0 @GlobalDescription This is a sample API for demonstrating OpenAPI generation with Gin and annotations.
@GlobalTitle My Service API @GlobalVersion 1.0.0 @GlobalDescription This is a sample API for demonstrating OpenAPI generation with Gin and annotations.
pkg
ui

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL