Fast, accurate, and developer-friendly OpenAPI 3.1 documentation generator for Go.
apidocs analyzes your Go source code to automatically generate OpenAPI 3.1 specifications and beautiful documentation sites. With incremental caching, accurate type inference, and multiple output formats.
- Features
- Installation
- Quick Start
- Supported Frameworks
- Comment Styles
- Configuration
- CLI Reference
- Documentation Themes
- Guides
- Type Inference
- Architecture
- Comparison with Alternatives
- Examples
- Contributing
- License
- OpenAPI 3.1 Native - Full specification compliance with modern features
- Incremental Analysis - Cached parsing for fast regeneration on changes
- Full Generics Support - Handles
T anyand constrained type parameters - Smart Type Inference - Extracts request/response types from handler signatures
- Multiple Router Support - Fiber, Gin, Echo, Chi, and net/http
- Multiple UI Themes - Swagger UI, Scalar, and custom themes
- Guides Support - Include markdown guides alongside API reference
- Code Samples - Auto-generated examples in multiple languages
- Try-It-Out - Interactive API testing with authentication support
- Mobile-Friendly - Responsive design with mobile navigation
- Hot Reload - Development server with automatic regeneration
- Swaggo Migration - Compatible annotation syntax for easy migration
- Natural Language Comments - Write documentation in plain English
- Validation Tags - Automatic schema validation from struct tags
go install github.com/bitnob/apidocs/cmd/apidocs@latestgit clone https://github.com/bitnob/apidocs.git
cd apidocs
go install ./cmd/apidocsapidocs --version# Analyze current package and generate OpenAPI spec
apidocs generate ./...
# Specify output file
apidocs generate ./... -o openapi.yaml
# Output as JSON
apidocs generate ./... -o openapi.json --format json# Generate static documentation
apidocs docs ./... -o ./docs
# Use a specific theme
apidocs docs ./... -o ./docs --theme scalar
# Include guides from markdown files
apidocs docs ./... -o ./docs --guides ./docs/guides# Start with hot reload
apidocs serve ./... --port 8080
# Custom host binding
apidocs serve ./... --host 0.0.0.0 --port 3000apidocs automatically detects and extracts routes from popular Go web frameworks:
| Framework | Status | Detection Method |
|---|---|---|
| Fiber | Full | app.Get(), app.Post(), etc. |
| Gin | Full | r.GET(), r.POST(), groups |
| Echo | Full | e.GET(), e.POST(), etc. |
| Chi | Full | r.Get(), r.Route(), groups |
| net/http | Basic | http.HandleFunc(), mux.Handle() |
Each framework's path parameter syntax is automatically converted to OpenAPI format:
// Fiber: /users/:id -> /users/{id}
app.Get("/users/:id", GetUser)
// Gin: /users/:id -> /users/{id}
r.GET("/users/:id", GetUser)
// Chi: /users/{id} -> /users/{id} (native)
r.Get("/users/{id}", GetUser)apidocs supports multiple documentation styles to fit your preference:
For teams migrating from swaggo, the familiar annotation syntax works out of the box:
// CreateUser creates a new user.
//
// @Summary Create a new user
// @Description Creates a new user account with the provided details
// @Tags users
// @Accept json
// @Produce json
// @Param request body CreateUserRequest true "User creation data"
// @Success 201 {object} User "Created user"
// @Failure 400 {object} APIError "Validation error"
// @Failure 409 {object} APIError "Email already exists"
// @Security BearerAuth
// @Router /users [post]
func CreateUser(c *fiber.Ctx) error {
var req CreateUserRequest
if err := c.BodyParser(&req); err != nil {
return c.Status(400).JSON(APIError{Message: "Invalid request"})
}
// ...
}Write documentation naturally without special syntax:
// CreateUser creates a new user account.
//
// Validates the request body and creates a new user in the database.
// Returns 201 with the created user on success.
// Returns 400 if validation fails.
// Returns 409 if the email already exists.
func CreateUser(c *fiber.Ctx) error {
// ...
}For complex documentation, use YAML frontmatter:
/*
---
summary: Create user
description: Creates a new user account with full validation
tags: [users, admin]
security: [bearerAuth]
deprecated: false
---
Creates a new user account. The email must be unique across the system.
Passwords are hashed using bcrypt before storage.
*/
func CreateUser(c *fiber.Ctx) error {
// ...
}Create an apidocs.yaml file in your project root:
version: "1"
# Input configuration
input:
packages:
- ./cmd/api/...
- ./internal/handlers/...
exclude:
- "*_test.go"
- "internal/mock/*"
# OpenAPI metadata
info:
title: "My API"
version: "1.0.0"
description: |
Full API documentation for My API.
## Authentication
This API uses Bearer token authentication.
contact:
name: API Support
email: support@example.com
license:
name: MIT
url: https://opensource.org/licenses/MIT
# Server configuration
servers:
- url: https://api.example.com
description: Production
- url: https://staging-api.example.com
description: Staging
- url: http://localhost:8080
description: Development
# Security schemes
security:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
apiKey:
type: apiKey
in: header
name: X-API-Key
# Documentation output
docs:
theme: scalar # swagger, scalar, or custom
output: ./docs
logo: ./assets/logo.svg
favicon: ./assets/favicon.ico
colors:
primary: "#0066FF"
background: "#FFFFFF"
customCss: ./assets/custom.css
guides: ./docs/guides # Optional: directory with markdown guides
# Code samples
samples:
languages:
- curl
- go
- javascript
- python
authentication:
- bearerAuth
# Output formats
output:
openapi: ./openapi.yaml
postman: ./postman_collection.json
typescript: ./types.d.tsGenerate OpenAPI specification from Go source code.
apidocs generate [packages...] [flags]
Flags:
-o, --output string Output file path (default "openapi.yaml")
-f, --format string Output format: yaml or json (default "yaml")
-c, --config string Config file path (default "apidocs.yaml")
--no-cache Disable caching
-v, --verbose Verbose output
Examples:
apidocs generate ./...
apidocs generate ./cmd/api -o api.yaml
apidocs generate ./... --format json -o openapi.jsonGenerate documentation site from OpenAPI specification.
apidocs docs [packages...] [flags]
Flags:
-o, --output string Output directory (default "./docs")
-t, --theme string Theme: swagger, scalar (default "scalar")
--title string Documentation title
--guides string Guides directory path
--logo string Logo file path
-c, --config string Config file path
Examples:
apidocs docs ./... -o ./docs
apidocs docs ./... --theme swagger --title "My API"
apidocs docs ./... --guides ./docs/guidesStart development server with hot reload.
apidocs serve [packages...] [flags]
Flags:
-p, --port int Server port (default 8080)
-h, --host string Server host (default "localhost")
-t, --theme string Theme: swagger, scalar (default "scalar")
--no-open Don't open browser automatically
Examples:
apidocs serve ./...
apidocs serve ./... --port 3000
apidocs serve ./... --host 0.0.0.0Validate an OpenAPI specification file.
apidocs validate <file> [flags]
Examples:
apidocs validate openapi.yaml
apidocs validate api.jsonMigrate from swaggo annotations.
apidocs migrate [flags]
Flags:
--from string Source format: swaggo (default "swaggo")
--dry-run Preview changes without modifying files
Examples:
apidocs migrate --from swaggo ./...
apidocs migrate --dry-run ./...Modern, beautiful design with excellent code highlighting and try-it-out functionality.
apidocs docs ./... --theme scalarClassic Swagger UI interface familiar to many developers.
apidocs docs ./... --theme swaggerCustomize appearance with CSS:
docs:
theme: scalar
customCss: ./assets/custom.css
colors:
primary: "#0066FF"
background: "#FFFFFF"Include markdown guides alongside your API reference:
docs/
├── guides/
│ ├── getting-started.md
│ ├── authentication.md
│ └── errors.md
└── openapi.yaml
Each guide supports YAML frontmatter:
---
title: Getting Started
description: Quick start guide for the API
order: 1
---
# Getting Started
Welcome to the API! This guide will help you get started.
## Prerequisites
- An API key from the dashboard
- curl or an HTTP client
## Your First Request
```bash
curl -X GET https://api.example.com/v1/users \
-H "Authorization: Bearer YOUR_API_KEY"
## Type Inference
apidocs automatically extracts types from your handler code:
### Request Body Detection
```go
func CreateUser(c *fiber.Ctx) error {
var req CreateUserRequest // Detected as request body
if err := c.BodyParser(&req); err != nil {
return err
}
// ...
}
func GetUser(c *fiber.Ctx) error {
user := User{...}
return c.JSON(user) // Detected as response type
}Schema details are extracted from struct tags:
type CreateUserRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8,max=128"`
Name string `json:"name" validate:"required,min=2,max=100"`
Age int `json:"age,omitempty" validate:"gte=0,lte=150"`
}This generates:
CreateUserRequest:
type: object
required:
- email
- password
- name
properties:
email:
type: string
format: email
password:
type: string
minLength: 8
maxLength: 128
name:
type: string
minLength: 2
maxLength: 100
age:
type: integer
minimum: 0
maximum: 150
nullable: trueapidocs detects Go const enums:
type OrderStatus string
const (
OrderStatusPending OrderStatus = "pending"
OrderStatusProcessing OrderStatus = "processing"
OrderStatusShipped OrderStatus = "shipped"
OrderStatusDelivered OrderStatus = "delivered"
OrderStatusCancelled OrderStatus = "cancelled"
)This generates:
OrderStatus:
type: string
enum:
- pending
- processing
- shipped
- delivered
- cancelled┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Go Source │────>│ Analyzer │────>│ OpenAPI Spec │
│ (AST + Types) │ │ (Incremental) │ │ (JSON/YAML) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
┌───────────────────────────────┘
v
┌──────────────────────────────────────┐
│ Template Engine │
│ ┌────────┐ ┌────────┐ ┌──────────┐ │
│ │Swagger │ │ Scalar │ │ Custom │ │
│ │ UI │ │ Style │ │ Themes │ │
│ └────────┘ └────────┘ └──────────┘ │
└──────────────────────────────────────┘
│
v
┌──────────────────────────────────────┐
│ Output Formats │
│ - Static HTML documentation │
│ - OpenAPI JSON/YAML │
│ - Markdown guides support │
└──────────────────────────────────────┘
| Component | Purpose |
|---|---|
pkg/analyzer |
Go AST analysis and type extraction |
pkg/analyzer/router |
Framework-specific route detection |
pkg/analyzer/schema |
Go type to JSON Schema conversion |
pkg/comments |
Comment parsing (swaggo, natural, YAML) |
pkg/spec |
OpenAPI spec building and validation |
pkg/templates |
Documentation site generation |
| Feature | apidocs | swaggo | go-swagger |
|---|---|---|---|
| OpenAPI Version | 3.1 | 2.0/3.0 | 2.0 |
| Incremental Caching | Yes | No | No |
| Generics Support | Full | Partial | No |
| UI Themes | Multiple | Swagger only | Swagger only |
| Type Inference | Yes | No | No |
| Guides Support | Yes | No | No |
| Mobile-Friendly | Yes | No | No |
See examples/fiber-api for a complete Fiber application with:
- CRUD operations
- Authentication middleware
- Request validation
- Error handling
See examples/gin-api for a complete Gin application with:
- Router groups
- Path parameters
- Query parameters
- Request/response types
Contributions are welcome! Please see our Contributing Guide for details.
# Clone the repository
git clone https://github.com/bitnob/apidocs.git
cd apidocs
# Install dependencies
go mod download
# Run tests
go test ./...
# Build
go build ./cmd/apidocs# Generate docs for the Gin example
cd examples/gin-api
apidocs docs ./... -o ./docs
# Serve with hot reload
apidocs serve ./... --port 8080MIT License - see LICENSE for details.
Made with care by Clement Sam