Skip to content

profclems/apidocs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

apidocs

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.

Table of Contents

Features

Core Capabilities

  • OpenAPI 3.1 Native - Full specification compliance with modern features
  • Incremental Analysis - Cached parsing for fast regeneration on changes
  • Full Generics Support - Handles T any and constrained type parameters
  • Smart Type Inference - Extracts request/response types from handler signatures
  • Multiple Router Support - Fiber, Gin, Echo, Chi, and net/http

Documentation Generation

  • 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

Developer Experience

  • 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

Installation

Using Go Install

go install github.com/bitnob/apidocs/cmd/apidocs@latest

From Source

git clone https://github.com/bitnob/apidocs.git
cd apidocs
go install ./cmd/apidocs

Verify Installation

apidocs --version

Quick Start

Generate OpenAPI Spec

# 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 Documentation Site

# 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

Development Server

# Start with hot reload
apidocs serve ./... --port 8080

# Custom host binding
apidocs serve ./... --host 0.0.0.0 --port 3000

Supported Frameworks

apidocs 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()

Framework-Specific Path Parameters

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)

Comment Styles

apidocs supports multiple documentation styles to fit your preference:

Style 1: Swaggo-Compatible Annotations

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"})
    }
    // ...
}

Style 2: Natural Language (Preferred)

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 {
    // ...
}

Style 3: YAML Frontmatter

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 {
    // ...
}

Configuration

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.ts

CLI Reference

apidocs generate

Generate 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.json

apidocs docs

Generate 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/guides

apidocs serve

Start 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.0

apidocs validate

Validate an OpenAPI specification file.

apidocs validate <file> [flags]

Examples:
  apidocs validate openapi.yaml
  apidocs validate api.json

apidocs migrate

Migrate 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 ./...

Documentation Themes

Scalar (Default)

Modern, beautiful design with excellent code highlighting and try-it-out functionality.

apidocs docs ./... --theme scalar

Swagger UI

Classic Swagger UI interface familiar to many developers.

apidocs docs ./... --theme swagger

Custom Themes

Customize appearance with CSS:

docs:
  theme: scalar
  customCss: ./assets/custom.css
  colors:
    primary: "#0066FF"
    background: "#FFFFFF"

Guides

Include markdown guides alongside your API reference:

Directory Structure

docs/
├── guides/
│   ├── getting-started.md
│   ├── authentication.md
│   └── errors.md
└── openapi.yaml

Guide Format

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
    }
    // ...
}

Response Type Detection

func GetUser(c *fiber.Ctx) error {
    user := User{...}
    return c.JSON(user)  // Detected as response type
}

Struct Tags

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: true

Enum Support

apidocs 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

Architecture

┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│   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           │
         └──────────────────────────────────────┘

Core Components

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

Comparison with Alternatives

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

Examples

Fiber API

See examples/fiber-api for a complete Fiber application with:

  • CRUD operations
  • Authentication middleware
  • Request validation
  • Error handling

Gin API

See examples/gin-api for a complete Gin application with:

  • Router groups
  • Path parameters
  • Query parameters
  • Request/response types

Contributing

Contributions are welcome! Please see our Contributing Guide for details.

Development Setup

# 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

Running Examples

# Generate docs for the Gin example
cd examples/gin-api
apidocs docs ./... -o ./docs

# Serve with hot reload
apidocs serve ./... --port 8080

License

MIT License - see LICENSE for details.


Made with care by Clement Sam

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors