swagify

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2026 License: MIT Imports: 4 Imported by: 0

README

Swagify

Swagify is a modern, code-first OpenAPI 3.1 documentation package for Go web frameworks such as Fiber and Gin.

It helps Go developers build beautiful API documentation with a developer experience closer to FastAPI, Django REST Swagger, and other modern API tooling — without ugly Swagger comments or annotation-heavy setup.

With Swagify, you define your routes, request models, and response models in Go, and it generates:

  • OpenAPI 3.1 JSON
  • interactive API docs UI
  • component schemas
  • request/response documentation
  • query, path, and header parameter documentation
  • tags, summaries, descriptions, and security metadata

Why Swagify?

Traditional Swagger tooling in Go often relies on comment-based generation like this:

// @Summary Create user
// @Description create user
// @Tags users
// @Accept json
// @Produce json
// @Param body body CreateUserRequest true "User data"
// @Success 200 {object} User
// @Router /users [post]

That works, but it is verbose, fragile, and not very pleasant to maintain.

Swagify takes a different approach:

  • code-first
  • type-driven
  • clean route options
  • minimal boilerplate
  • modern docs UI
  • framework adapters for Fiber and Gin

Features

  • OpenAPI 3.1 generation
  • Fiber support
  • Gin support
  • route-level summaries, descriptions, tags, and operation IDs
  • request and response model documentation
  • query, path, and header parameter documentation
  • custom success and error responses
  • security documentation helpers
  • modern embedded docs UI
  • no filesystem-relative static docs dependency
  • no Swagger comments required

Installation

go get github.com/mrgofurov/swagify

Replace the module path above with your real repository path.

Quick Start

Fiber
package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/mrgofurov/swagify"
	"github.com/mrgofurov/swagify/core"
)

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

type ErrorResponse struct {
	Message string `json:"message"`
}

func getUser(c *fiber.Ctx) error {
	id := c.Params("id")

	return c.JSON(UserResponse{
		ID:    1,
		Name:  "Ali",
		Email: "ali@example.com",
		_ = id,
	})
}

func main() {
	app := fiber.New()

	api := swagify.NewFiber(app, swagify.FiberConfig{
		Info: &core.Info{
			Title:       "User API",
			Description: "Example API documented with Swagify",
			Version:     "1.0.0",
		},
	})

	api.GET("/users/:id", getUser,
		swagify.Summary("Get user by ID"),
		swagify.Description("Returns a single user by its unique identifier."),
		swagify.Tags("Users"),
		swagify.WithResponse(UserResponse{}),
		swagify.ErrorResponse(404, ErrorResponse{}, "User not found"),
	)

	api.RegisterOpenAPI("/openapi.json")
	api.RegisterDocs("/docs")

	log.Fatal(app.Listen(":8080"))
}

Open:

Docs UI: http://localhost:8080/docs

OpenAPI JSON: http://localhost:8080/openapi.json

Gin
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/mrgofurov/swagify"
)

type UserResponse struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func getUser(c *gin.Context) {
	c.JSON(http.StatusOK, UserResponse{
		ID:   1,
		Name: "Ali",
	})
}

func main() {
	r := gin.Default()

	api := swagify.NewGin(r)

	api.GET("/users/:id", getUser,
		swagify.Summary("Get user by ID"),
		swagify.Tags("Users"),
		swagify.WithResponse(UserResponse{}),
	)

	api.RegisterOpenAPI("/openapi.json")
	api.RegisterDocs("/docs")

	r.Run(":8080")
}

Basic Usage

Documenting a GET endpoint
api.GET("/users/:id", getUser,
	swagify.Summary("Get user by ID"),
	swagify.Description("Returns a single user by their unique identifier."),
	swagify.Tags("Users"),
	swagify.WithResponse(UserResponse{}),
	swagify.ErrorResponse(404, ErrorResponse{}, "User not found"),
)
Documenting a POST endpoint
api.POST("/users", createUser,
	swagify.Summary("Create a new user"),
	swagify.Description("Creates a new user with the provided information."),
	swagify.Tags("Users"),
	swagify.WithRequest(CreateUserRequest{}),
	swagify.WithResponse(UserResponse{}),
	swagify.SuccessStatus(201),
	swagify.ErrorResponse(400, ErrorResponse{}, "Invalid request body"),
)

Auto-Discovery (Zero Migration)

Already have a Fiber or Gin project with hundreds of routes? No need to rewrite them. Use Discover() to auto-generate documentation from your existing routes:

Fiber
// Your existing app — nothing changes here
app := fiber.New()
app.Get("/users", listUsers)
app.Get("/users/:id", getUser)
app.Post("/users", createUser)
app.Put("/users/:id", updateUser)
app.Delete("/users/:id", deleteUser)

// Attach Swagify and auto-discover all routes
api := swagify.NewFiber(app, swagify.FiberConfig{
    Info: &core.Info{
        Title:   "My API",
        Version: "1.0.0",
    },
})
api.Discover()

api.RegisterOpenAPI()
api.RegisterDocs()
log.Fatal(app.Listen(":8080"))
Gin
r := gin.Default()
r.GET("/products", listProducts)
r.POST("/products", createProduct)

api := swagify.NewGin(r)
api.Discover()

api.RegisterOpenAPI()
api.RegisterDocs()
r.Run(":8080")
Enriching Discovered Routes

After discovery, you can optionally enrich specific routes with request/response types and metadata:

api.Discover()

// Add rich documentation to specific routes
api.Enrich("GET /users",
    swagify.Summary("List all users"),
    swagify.Tags("Users"),
    swagify.WithResponse(UserListResponse{}),
    swagify.QueryParams(ListUsersQuery{}),
)

api.Enrich("POST /users",
    swagify.Summary("Create a new user"),
    swagify.Tags("Users"),
    swagify.WithRequest(CreateUserRequest{}),
    swagify.WithResponse(UserResponse{}),
)
Discovery Options

Control which routes are discovered:

api.Discover(swagify.DiscoverOptions{
    // Only document routes under /api
    IncludePaths: []string{"/api"},

    // Skip health/metrics endpoints
    ExcludePaths: []string{"/internal", "/metrics"},
})
What Discover Auto-Generates

Even without enrichment, Discover() generates useful documentation:

Route Auto Summary Auto Tag
GET /users List users Users
GET /users/:id Get user by id Users
POST /users Create user Users
PUT /users/:id Update user by id Users
DELETE /users/:id Delete user by id Users
GET /api/v1/orders List orders Orders

Protecting Docs with BasicAuth

Protect your /docs and /openapi.json endpoints with HTTP Basic Authentication:

api := swagify.NewFiber(app)

// Simple — just username and password
api.BasicAuth("admin", "secret123")

api.RegisterOpenAPI()  // protected
api.RegisterDocs()     // protected

With a custom realm (shown in the browser prompt):

api.BasicAuth("admin", "secret123", swagify.DocsAuthConfig{
    Realm: "My API Documentation",
})

Note: BasicAuth() must be called before RegisterOpenAPI() and RegisterDocs(). It only protects the docs endpoints — your API routes remain unaffected.

Documentation

Overview

Package swagify provides automatic OpenAPI 3.1 documentation generation for Go web frameworks including Fiber and Gin.

Swagify takes a code-first approach: define your types and handlers, and swagify generates a complete OpenAPI specification with a beautiful interactive docs UI — no comments or annotations required.

Quick start with Fiber:

app := fiber.New()
api := swagify.NewFiber(app)

api.POST("/users", createUserHandler,
    swagify.Summary("Create a user"),
    swagify.Tags("Users"),
    swagify.WithRequest(CreateUserRequest{}),
    swagify.WithResponse(UserResponse{}),
)

api.RegisterOpenAPI()
api.RegisterDocs()
app.Listen(":8080")

Quick start with Gin:

r := gin.Default()
api := swagify.NewGin(r)

api.POST("/users", createUserHandler,
    swagify.Summary("Create a user"),
    swagify.Tags("Users"),
)

api.RegisterOpenAPI()
api.RegisterDocs()
r.Run(":8080")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DELETE

func DELETE[Req any, Res any](f *router.FiberAdapter, path string, handler func(*fiber.Ctx, Req) (Res, error), opts ...RouteOption)

DELETE registers a typed DELETE handler for Fiber with automatic schema inference.

func GET

func GET[Req any, Res any](f *router.FiberAdapter, path string, handler func(*fiber.Ctx, Req) (Res, error), opts ...RouteOption)

GET registers a typed GET handler for Fiber with automatic schema inference.

func NewFiber

func NewFiber(app *fiber.App, configs ...router.FiberConfig) *router.FiberAdapter

NewFiber creates a new swagify adapter for the Fiber web framework.

func NewGin

func NewGin(engine *gin.Engine, configs ...router.GinConfig) *router.GinAdapter

NewGin creates a new swagify adapter for the Gin web framework.

func PATCH

func PATCH[Req any, Res any](f *router.FiberAdapter, path string, handler func(*fiber.Ctx, Req) (Res, error), opts ...RouteOption)

PATCH registers a typed PATCH handler for Fiber with automatic schema inference.

func POST

func POST[Req any, Res any](f *router.FiberAdapter, path string, handler func(*fiber.Ctx, Req) (Res, error), opts ...RouteOption)

POST registers a typed POST handler for Fiber with automatic schema inference.

func PUT

func PUT[Req any, Res any](f *router.FiberAdapter, path string, handler func(*fiber.Ctx, Req) (Res, error), opts ...RouteOption)

PUT registers a typed PUT handler for Fiber with automatic schema inference.

Types

type Contact

type Contact = core.Contact

Contact represents API contact information.

type DiscoverOptions

type DiscoverOptions = router.DiscoverOptions

DiscoverOptions configures how route auto-discovery behaves.

type DocsAuthConfig

type DocsAuthConfig = router.DocsAuthConfig

DocsAuthConfig holds credentials for protecting the docs and OpenAPI endpoints.

type FiberConfig

type FiberConfig = router.FiberConfig

FiberConfig holds configuration for the Fiber adapter.

type GinConfig

type GinConfig = router.GinConfig

GinConfig holds configuration for the Gin adapter.

type Info

type Info = core.Info

Info represents API information metadata.

type License

type License = core.License

License represents API license information.

type RouteOption

type RouteOption = router.RouteOption

RouteOption configures a route's documentation metadata.

func Deprecated

func Deprecated() RouteOption

Deprecated marks the operation as deprecated.

func Description

func Description(d string) RouteOption

Description sets the operation description.

func ErrorResponse

func ErrorResponse(status int, model any, description string) RouteOption

ErrorResponse adds an error response definition.

func HeaderParams

func HeaderParams(model any) RouteOption

HeaderParams sets the header parameters type for documentation.

func OperationID

func OperationID(id string) RouteOption

OperationID sets a custom operation ID.

func PathParams

func PathParams(model any) RouteOption

PathParams sets the path parameters type for documentation.

func QueryParams

func QueryParams(model any) RouteOption

QueryParams sets the query parameters type for documentation.

func RequestContentType

func RequestContentType(ct string) RouteOption

RequestContentType overrides the request content type.

func Response

func Response(status int, model any, description string) RouteOption

Response adds a custom response definition for a status code.

func ResponseContentType

func ResponseContentType(ct string) RouteOption

ResponseContentType overrides the response content type.

func Security

func Security(schemes ...map[string][]string) RouteOption

Security sets security requirements for a route.

func SecurityAPIKey

func SecurityAPIKey() RouteOption

SecurityAPIKey adds API key security requirement to a route.

func SecurityBasic

func SecurityBasic() RouteOption

SecurityBasic adds basic auth security requirement to a route.

func SecurityBearer

func SecurityBearer() RouteOption

SecurityBearer adds bearer token security requirement to a route.

func SuccessStatus

func SuccessStatus(code int) RouteOption

SuccessStatus sets the default success status code.

func Summary

func Summary(s string) RouteOption

Summary sets the operation summary.

func Tags

func Tags(tags ...string) RouteOption

Tags sets the operation tags for grouping.

func WithRequest

func WithRequest(model any) RouteOption

WithRequest sets the request body type for untyped handlers.

func WithResponse

func WithResponse(model any) RouteOption

WithResponse sets the response body type for untyped handlers.

type SecurityScheme

type SecurityScheme = core.SecurityScheme

SecurityScheme represents a security scheme definition.

type Server

type Server = core.Server

Server represents an API server.

type Tag

type Tag = core.Tag

Tag represents an API tag for grouping operations.

Directories

Path Synopsis
Package core provides type reflection and JSON Schema generation for the swagify OpenAPI documentation package.
Package core provides type reflection and JSON Schema generation for the swagify OpenAPI documentation package.
examples
auth command
Auth example demonstrating JWT and API key security documentation with swagify.
Auth example demonstrating JWT and API key security documentation with swagify.
fiber-basic command
Fiber basic CRUD example demonstrating swagify with standard Fiber handlers.
Fiber basic CRUD example demonstrating swagify with standard Fiber handlers.
fiber-discover command
Example: Fiber Auto-Discovery
Example: Fiber Auto-Discovery
fiber-typed command
Fiber typed handlers example demonstrating swagify generics-based type inference.
Fiber typed handlers example demonstrating swagify generics-based type inference.
gin-basic command
Gin basic CRUD example demonstrating swagify with Gin framework.
Gin basic CRUD example demonstrating swagify with Gin framework.
gin-discover command
Example: Gin Auto-Discovery
Example: Gin Auto-Discovery
nested-schemas command
Nested schemas example demonstrating complex type handling.
Nested schemas example demonstrating complex type handling.
internal
cache
Package cache provides a thread-safe schema cache for the swagify package.
Package cache provides a thread-safe schema cache for the swagify package.
errors
Package errors provides structured error types for the swagify package.
Package errors provides structured error types for the swagify package.
utils
Package utils provides internal utility functions for the swagify package.
Package utils provides internal utility functions for the swagify package.
Package openapi provides OpenAPI 3.1 document generation from the swagify route registry and schema generator.
Package openapi provides OpenAPI 3.1 document generation from the swagify route registry and schema generator.
Package router provides route registration, metadata collection, and framework adapter interfaces for the swagify documentation package.
Package router provides route registration, metadata collection, and framework adapter interfaces for the swagify documentation package.
Package ui provides embedded API documentation UI assets and handler registration for multiple web frameworks.
Package ui provides embedded API documentation UI assets and handler registration for multiple web frameworks.

Jump to

Keyboard shortcuts

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