openapi

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 13 Imported by: 1

README

OpenAPI Documentation Generator

This package was created for Apiright. The current state is a work in progress, mainly AI slop. I will look more into it, after Apiright is stable! As long as this version is under 1.0.0, use on your risk.

A comprehensive OpenAPI 3.0 documentation generator for Go applications. This package provides automatic schema generation from Go types, endpoint documentation, and multiple output formats including JSON, YAML, and HTML with Swagger UI.

Features

  • 🚀 OpenAPI 3.0 Specification Generation: Full support for OpenAPI 3.0 spec
  • 🔄 Automatic Schema Generation: Generate schemas from Go structs using reflection
  • 📝 Endpoint Registration: Functions to register endpoints with full documentation
  • 📊 Multiple Output Formats: JSON, YAML, and HTML documentation
  • 🎨 Swagger UI Integration: Generate beautiful Swagger UI documentation
  • Validation: Validate the generated OpenAPI spec
  • 🔥 Hot Reload: Support for regenerating docs during development
  • 🏗️ Builder Pattern: Fluent API for building endpoint documentation
  • 🔐 Security Schemes: Support for various authentication methods
  • 📋 CRUD Generation: Automatic CRUD endpoint generation
  • 🏷️ Tag Management: Organize endpoints with tags
  • 📈 Statistics: Get insights about your API documentation

Installation

go get github.com/bata94/openapi

Quick Start

package main

import (
    "log"
    "reflect"
    "time"
)

type User struct {
    ID       string    `json:"id" description:"User ID"`
    Username string    `json:"username" description:"Username"`
    Email    string    `json:"email" description:"Email address"`
    Created  time.Time `json:"created_at" description:"Creation timestamp"`
}

func main() {
    // Create a generator with quick start
    generator := openapi.QuickStart("My API", "A sample API", "1.0.0")

    // Add health check endpoint
    openapi.HealthCheckEndpoint(generator)

    // Add authentication endpoints
    openapi.AuthEndpoints(generator)

    // Add CRUD endpoints for users
    openapi.CRUDEndpoints(generator, "/users", reflect.TypeOf(User{}), "users")

    // Add a custom endpoint
    customBuilder := openapi.NewEndpointBuilder().
        Summary("Get user statistics").
        Description("Returns statistics about user activity").
        Tags("users", "analytics").
        PathParam("id", "User ID", reflect.TypeOf("")).
        QueryParam("period", "Time period for statistics", false, reflect.TypeOf("")).
        Security(openapi.SecurityRequirement{"BearerAuth": []string{}}).
        Response(200, "User statistics", "application/json", nil)

    generator.AddEndpointWithBuilder("GET", "/users/{id}/stats", customBuilder)

    // Generate and write documentation
    writer := openapi.NewWriter(generator)
    if err := writer.WriteFiles(); err != nil {
        log.Fatal(err)
    }

    // Or serve the documentation
    // openapi.SimpleServe(generator.config.OutputDir, 8080)
}

Core Concepts

Generator

The Generator is the main component that manages the OpenAPI specification:

// Create with default config
config := openapi.DefaultConfig()
config.Title = "My API"
config.Description = "API description"
config.Version = "1.0.0"

generator := openapi.NewGenerator(config)

// Or use quick start
generator := openapi.QuickStart("My API", "API description", "1.0.0")
Endpoint Builder

Use the builder pattern to create detailed endpoint documentation:

builder := openapi.NewEndpointBuilder().
    Summary("Create user").
    Description("Create a new user account").
    Tags("users").
    RequestType(reflect.TypeOf(CreateUserRequest{})).
    Response(201, "User created", "application/json", reflect.TypeOf(User{})).
    Response(400, "Invalid input", "application/json", reflect.TypeOf(ErrorResponse{}))

generator.AddEndpointWithBuilder("POST", "/users", builder)
Schema Generation

Automatic schema generation from Go types:

type User struct {
    ID       string    `json:"id" description:"User ID"`
    Username string    `json:"username" validate:"required" description:"Username"`
    Email    string    `json:"email" validate:"required,email" description:"Email"`
    IsActive bool      `json:"is_active" description:"Active status"`
    Created  time.Time `json:"created_at" description:"Creation time"`
}

// Schema is automatically generated when you use the type
builder.RequestType(reflect.TypeOf(User{}))

Advanced Usage

Custom Configuration
config := openapi.Config{
    Title:           "Advanced API",
    Description:     "Advanced API with custom configuration",
    Version:         "2.0.0",
    OutputDir:       "./docs",
    GenerateJSON:    true,
    GenerateYAML:    true,
    GenerateHTML:    true,
    PrettyPrint:     true,
    UseReferences:   true,
    IncludeExamples: true,
    ValidateSchemas: true,
}

generator := openapi.NewGenerator(config)
Security Schemes
// Add JWT Bearer authentication
generator.AddSecurityScheme("BearerAuth", openapi.SecurityScheme{
    Type:         "http",
    Scheme:       "bearer",
    BearerFormat: "JWT",
    Description:  "JWT Bearer token authentication",
})

// Add API Key authentication
generator.AddSecurityScheme("ApiKeyAuth", openapi.SecurityScheme{
    Type:        "apiKey",
    In:          "header",
    Name:        "X-API-Key",
    Description: "API key authentication",
})

// Use in endpoints
builder.Security(openapi.SecurityRequirement{"BearerAuth": []string{}})
Servers
generator.AddServer(openapi.Server{
    URL:         "https://api.example.com/v1",
    Description: "Production server",
})

generator.AddServer(openapi.Server{
    URL:         "https://staging-api.example.com/v1",
    Description: "Staging server",
})
Tags
generator.AddTag(openapi.Tag{
    Name:        "users",
    Description: "User management operations",
})

generator.AddTag(openapi.Tag{
    Name:        "auth",
    Description: "Authentication operations",
})
Complex Endpoints
builder := openapi.NewEndpointBuilder().
    Summary("Advanced user search").
    Description("Search users with advanced filtering and pagination").
    Tags("users", "search").
    QueryParam("q", "Search query", false, reflect.TypeOf("")).
    QueryParam("page", "Page number", false, reflect.TypeOf(1)).
    QueryParam("limit", "Items per page", false, reflect.TypeOf(20)).
    QueryParam("sort", "Sort field and direction", false, reflect.TypeOf("")).
    QueryParam("filter", "Filter criteria", false, reflect.TypeOf("")).
    HeaderParam("X-Request-ID", "Request ID", false, reflect.TypeOf("")).
    Security(openapi.SecurityRequirement{"BearerAuth": []string{}}).
    Response(200, "Search results", "application/json", reflect.TypeOf(UserListResponse{})).
    Response(400, "Invalid query", "application/json", reflect.TypeOf(ErrorResponse{})).
    Response(401, "Unauthorized", "application/json", reflect.TypeOf(ErrorResponse{}))

generator.AddEndpointWithBuilder("GET", "/users/search", builder)
Request/Response Examples
builder := openapi.NewEndpointBuilder().
    Summary("Create user").
    RequestType(reflect.TypeOf(CreateUserRequest{})).
    RequestExample(CreateUserRequest{
        Username:  "johndoe",
        Email:     "[email protected]",
        FirstName: "John",
        LastName:  "Doe",
    }).
    Response(201, "User created", "application/json", reflect.TypeOf(User{})).
    ResponseExample(User{
        ID:       "user_123",
        Username: "johndoe",
        Email:    "[email protected]",
        Created:  time.Now(),
    })

Validation Tags

The package supports various validation tags for automatic schema validation:

type CreateUserRequest struct {
    Username string `json:"username" validate:"required,min=3,max=50" description:"Username"`
    Email    string `json:"email" validate:"required,email" description:"Email address"`
    Age      int    `json:"age" validate:"min=18,max=120" description:"User age"`
    Website  string `json:"website" validate:"url" description:"Personal website"`
}

Supported validation tags:

  • required - Field is required
  • min=N - Minimum value/length
  • max=N - Maximum value/length
  • email - Email format
  • url - URL format
  • len=N - Exact length

Output Formats

JSON
writer := openapi.NewWriter(generator)
writer.WriteToFile("./api.json", "json")
YAML
writer.WriteToFile("./api.yaml", "yaml")
HTML with Swagger UI
writer.WriteToFile("./api.html", "html")
Markdown Documentation
writer.GenerateMarkdownDocs()

Utility Functions

CRUD Generation
// Generates complete CRUD endpoints for a resource
openapi.CRUDEndpoints(generator, "/users", reflect.TypeOf(User{}), "users")
Standard Endpoints
// Add health check endpoint
openapi.HealthCheckEndpoint(generator)

// Add authentication endpoints
openapi.AuthEndpoints(generator)
Helper Functions
// Pointer helpers for optional fields
name := openapi.StringPtr("optional name")
count := openapi.IntPtr(42)
price := openapi.Float64Ptr(19.99)
active := openapi.BoolPtr(true)

// Common parameters
params := openapi.PaginationParams()
filters := openapi.FilterParams()
headers := openapi.CommonHeaders()

Middleware

Automatic endpoint documentation middleware:

generator := openapi.QuickStart("Auto API", "Auto-documented API", "1.0.0")
middleware := openapi.Middleware(generator)

// Use with your HTTP router
router.Use(middleware)

Statistics

Get insights about your API documentation:

stats := generator.GetStatistics()
fmt.Printf("Total endpoints: %d\n", stats.TotalEndpoints)
fmt.Printf("Total schemas: %d\n", stats.TotalSchemas)
fmt.Printf("Endpoints by method: %v\n", stats.EndpointsByMethod)
fmt.Printf("Endpoints by tag: %v\n", stats.EndpointsByTag)

Serving Documentation

Simple Server
// Generate and serve documentation on port 8080
openapi.GenerateAndServe(generator, 8080)
Custom Server
writer := openapi.NewWriter(generator)
writer.WriteFiles()

// Serve with your own server
http.Handle("/docs/", http.StripPrefix("/docs/", http.FileServer(http.Dir("./docs"))))

Best Practices

  1. Use Descriptive Names: Provide clear summaries and descriptions for endpoints
  2. Tag Organization: Use tags to group related endpoints
  3. Validation Tags: Use struct tags for automatic validation
  4. Examples: Provide examples for better documentation
  5. Security: Document security requirements for protected endpoints
  6. Error Responses: Document all possible error responses
  7. Versioning: Include version information in your API

Examples

See the example_test.go file for comprehensive examples including:

  • Basic usage
  • Advanced endpoints
  • Schema generation
  • File generation
  • CRUD generation
  • Custom validation
  • Complete workflows

Testing

Run the tests:

go test ./...

Run benchmarks:

go test -bench=. ./...

License

This package is under the MIT license. See the LICENSE file for details. If another License is desired, please contact the author.

Documentation

Overview

Package openapi provides comprehensive OpenAPI 3.0 documentation generation for Go web applications. It supports automatic schema generation from Go types, endpoint documentation, and multiple output formats including JSON, YAML, and HTML.

Index

Constants

View Source
const Version = "0.1.0"

Version of the OpenAPI generator package

Variables

This section is empty.

Functions

func AuthEndpoints

func AuthEndpoints(generator *Generator) error

AuthEndpoints creates standard authentication endpoints

func BoolPtr

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to a bool

func CRUDEndpoints

func CRUDEndpoints(generator *Generator, basePath string, resourceType reflect.Type, resourceName string) error

CRUDEndpoints creates a complete set of CRUD endpoints for a resource

func CommonHeaders

func CommonHeaders() map[string]HeaderInfo

CommonHeaders returns common HTTP headers for API responses

func ExampleUsage

func ExampleUsage()

ExampleUsage demonstrates how to use the OpenAPI generator

func Float64Ptr

func Float64Ptr(f float64) *float64

Float64Ptr returns a pointer to a float64

func GenerateAndServe

func GenerateAndServe(generator *Generator, port int) error

GenerateAndServe generates documentation and starts a simple HTTP server to serve it

func GenerateExample

func GenerateExample(schema Schema) any

GenerateExample generates an example value for a schema

func GeneratedAt

func GeneratedAt() string

GeneratedAt returns the current timestamp for documentation generation

func HTTPMethodFromString

func HTTPMethodFromString(method string) string

HTTPMethodFromString converts a string to an HTTP method

func HealthCheckEndpoint

func HealthCheckEndpoint(generator *Generator) error

HealthCheckEndpoint creates a standard health check endpoint

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to an int

func IsValidHTTPMethod

func IsValidHTTPMethod(method string) bool

IsValidHTTPMethod checks if a method is a valid HTTP method

func SimpleServe

func SimpleServe(outputDir string, port int) error

func StandardResponses

func StandardResponses() map[int]ResponseInfo

StandardResponses returns common HTTP response definitions

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to a string (useful for optional schema fields)

func ValidateRequest

func ValidateRequest(generator *Generator, method, path string, body any) error

ValidateRequest validates a request against the OpenAPI specification

func ValidateSchema

func ValidateSchema(schema Schema) error

ValidateSchema performs basic validation on a schema

Types

type Callback

type Callback map[string]PathItem

Callback is a map of possible out-of band callbacks related to the parent operation

type Components

type Components struct {
	Schemas         map[string]Schema         `json:"schemas,omitempty" yaml:"schemas,omitempty"`
	Responses       map[string]Response       `json:"responses,omitempty" yaml:"responses,omitempty"`
	Parameters      map[string]Parameter      `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	Examples        map[string]Example        `json:"examples,omitempty" yaml:"examples,omitempty"`
	RequestBodies   map[string]RequestBody    `json:"requestBodies,omitempty" yaml:"requestBodies,omitempty"`
	Headers         map[string]Header         `json:"headers,omitempty" yaml:"headers,omitempty"`
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"`
	Links           map[string]Link           `json:"links,omitempty" yaml:"links,omitempty"`
	Callbacks       map[string]Callback       `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`
}

Components holds a set of reusable objects for different aspects of the OAS

type Config

type Config struct {
	// API Information
	Title          string
	Description    string
	Version        string
	TermsOfService string
	Contact        *Contact
	License        *License

	// Server Information
	Servers []Server

	// Security
	SecuritySchemes map[string]SecurityScheme
	GlobalSecurity  []SecurityRequirement

	// Tags
	Tags []Tag

	// External Documentation
	ExternalDocs *ExternalDocumentation

	// Output Configuration
	OutputDir    string
	GenerateJSON bool
	GenerateYAML bool
	GenerateHTML bool
	PrettyPrint  bool

	// Schema Generation Options
	UseReferences     bool
	IncludeExamples   bool
	ValidateSchemas   bool
	CustomTypeMapping map[reflect.Type]Schema
}

Config contains configuration for the OpenAPI generator

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration

type Contact

type Contact struct {
	Name  string `json:"name,omitempty" yaml:"name,omitempty"`
	URL   string `json:"url,omitempty" yaml:"url,omitempty"`
	Email string `json:"email,omitempty" yaml:"email,omitempty"`
}

Contact information for the exposed API

type Encoding

type Encoding struct {
	ContentType   string            `json:"contentType,omitempty" yaml:"contentType,omitempty"`
	Headers       map[string]Header `json:"headers,omitempty" yaml:"headers,omitempty"`
	Style         string            `json:"style,omitempty" yaml:"style,omitempty"`
	Explode       *bool             `json:"explode,omitempty" yaml:"explode,omitempty"`
	AllowReserved bool              `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"`
}

Encoding defines encoding definition applied to a single schema property

type EndpointBuilder

type EndpointBuilder struct {
	// contains filtered or unexported fields
}

EndpointBuilder helps build endpoint documentation

func NewEndpointBuilder

func NewEndpointBuilder() *EndpointBuilder

NewEndpointBuilder creates a new endpoint builder

func RESTEndpoint

func RESTEndpoint(method, path, summary string, resourceType reflect.Type) *EndpointBuilder

RESTEndpoint creates a REST endpoint with standard responses

func SimpleEndpoint

func SimpleEndpoint(method, path, summary string) *EndpointBuilder

SimpleEndpoint creates a simple endpoint with minimal configuration

func (*EndpointBuilder) Build

func (eb *EndpointBuilder) Build() EndpointOptions

Build builds the endpoint options

func (*EndpointBuilder) ConvertToOperation

func (eb *EndpointBuilder) ConvertToOperation() Operation

ConvertToOperation converts endpoint options to an OpenAPI operation

func (*EndpointBuilder) Deprecated

func (eb *EndpointBuilder) Deprecated() *EndpointBuilder

Deprecated marks the endpoint as deprecated

func (*EndpointBuilder) Description

func (eb *EndpointBuilder) Description(description string) *EndpointBuilder

Description sets the endpoint description

func (*EndpointBuilder) HeaderParam

func (eb *EndpointBuilder) HeaderParam(name, description string, required bool, t reflect.Type) *EndpointBuilder

HeaderParam adds a header parameter

func (*EndpointBuilder) OperationID

func (eb *EndpointBuilder) OperationID(id string) *EndpointBuilder

OperationID sets the operation ID

func (*EndpointBuilder) PathParam

func (eb *EndpointBuilder) PathParam(name, description string, t reflect.Type) *EndpointBuilder

PathParam adds a path parameter

func (*EndpointBuilder) QueryParam

func (eb *EndpointBuilder) QueryParam(name, description string, required bool, t reflect.Type) *EndpointBuilder

QueryParam adds a query parameter

func (*EndpointBuilder) RequestBody

func (eb *EndpointBuilder) RequestBody(description string, required bool, contentTypes []string, t reflect.Type) *EndpointBuilder

RequestBody sets the request body information

func (*EndpointBuilder) RequestExample

func (eb *EndpointBuilder) RequestExample(example any) *EndpointBuilder

RequestExample sets the request example

func (*EndpointBuilder) RequestType

func (eb *EndpointBuilder) RequestType(t reflect.Type) *EndpointBuilder

RequestType sets the request body type

func (*EndpointBuilder) Response

func (eb *EndpointBuilder) Response(statusCode int, description string, contentTypes []string, t reflect.Type) *EndpointBuilder

Response adds a response definition

func (*EndpointBuilder) ResponseExample

func (eb *EndpointBuilder) ResponseExample(example any) *EndpointBuilder

ResponseExample sets the response example

func (*EndpointBuilder) ResponseHeader

func (eb *EndpointBuilder) ResponseHeader(statusCode int, name, description string, t reflect.Type) *EndpointBuilder

ResponseHeader adds a header to a response

func (*EndpointBuilder) ResponseType

func (eb *EndpointBuilder) ResponseType(t reflect.Type) *EndpointBuilder

ResponseType sets the response type

func (*EndpointBuilder) Security

func (eb *EndpointBuilder) Security(requirements ...SecurityRequirement) *EndpointBuilder

Security adds security requirements

func (*EndpointBuilder) Summary

func (eb *EndpointBuilder) Summary(summary string) *EndpointBuilder

Summary sets the endpoint summary

func (*EndpointBuilder) Tags

func (eb *EndpointBuilder) Tags(tags ...string) *EndpointBuilder

Tags sets the endpoint tags

type EndpointOptions

type EndpointOptions struct {
	// Basic information
	Summary     string
	Description string
	Tags        []string
	OperationID string
	Deprecated  bool

	// Request/Response types
	RequestType  reflect.Type
	ResponseType reflect.Type

	// Parameters
	PathParams   []ParameterInfo
	QueryParams  []ParameterInfo
	HeaderParams []ParameterInfo

	// Request body
	RequestBody *RequestBodyInfo

	// Responses
	Responses map[int]ResponseInfo

	// Security
	Security []SecurityRequirement

	// Examples
	RequestExample  any
	ResponseExample any
}

EndpointOptions contains all the options for documenting an endpoint

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error" description:"Error message"`
	Code    int    `json:"code" description:"Error code"`
	Details string `json:"details,omitempty" description:"Additional error details"`
}

ErrorResponse represents a standard error response

type Example

type Example struct {
	Summary       string `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description   string `json:"description,omitempty" yaml:"description,omitempty"`
	Value         any    `json:"value,omitempty" yaml:"value,omitempty"`
	ExternalValue string `json:"externalValue,omitempty" yaml:"externalValue,omitempty"`
}

Example object

type ExternalDocumentation

type ExternalDocumentation struct {
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
	URL         string `json:"url" yaml:"url"`
}

ExternalDocumentation allows referencing an external resource for extended documentation

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator is the main OpenAPI documentation generator

func NewBasicGenerator

func NewBasicGenerator(title, description, version string) *Generator

func NewGenerator

func NewGenerator(config Config) *Generator

NewGenerator creates a new OpenAPI generator

func QuickStart

func QuickStart(title, description, version string) *Generator

QuickStart creates a generator with sensible defaults and basic configuration

func (*Generator) AddCustomParameter

func (g *Generator) AddCustomParameter(name string, parameter Parameter)

AddCustomParameter adds a custom parameter to the components

func (*Generator) AddCustomResponse

func (g *Generator) AddCustomResponse(name string, response Response)

AddCustomResponse adds a custom response to the components

func (*Generator) AddCustomSchema

func (g *Generator) AddCustomSchema(name string, schema Schema)

AddCustomSchema adds a custom schema to the components

func (*Generator) AddEndpoint

func (g *Generator) AddEndpoint(method, path string, options EndpointOptions) error

AddEndpoint adds an endpoint to the documentation

func (*Generator) AddEndpointWithBuilder

func (g *Generator) AddEndpointWithBuilder(method, path string, builder *EndpointBuilder) error

AddEndpointWithBuilder adds an endpoint using the builder pattern

func (*Generator) AddGlobalSecurity

func (g *Generator) AddGlobalSecurity(requirements ...SecurityRequirement)

AddGlobalSecurity adds global security requirements

func (*Generator) AddSecurityScheme

func (g *Generator) AddSecurityScheme(name string, scheme SecurityScheme)

AddSecurityScheme adds a security scheme

func (*Generator) AddServer

func (g *Generator) AddServer(server Server)

AddServer adds a server to the specification

func (*Generator) AddTag

func (g *Generator) AddTag(tag Tag)

AddTag adds a tag to the specification

func (*Generator) Clone

func (g *Generator) Clone() *Generator

Clone creates a copy of the generator

func (*Generator) GenerateSpec

func (g *Generator) GenerateSpec() (*OpenAPISpec, error)

GenerateSpec generates the complete OpenAPI specification

func (*Generator) GetEndpoint

func (g *Generator) GetEndpoint(method, path string) (EndpointOptions, bool)

GetEndpoint retrieves an endpoint's documentation

func (*Generator) GetOutputPath

func (g *Generator) GetOutputPath(filename string) string

GetOutputPath returns the full output path for a given filename

func (*Generator) GetSchemaGenerator

func (g *Generator) GetSchemaGenerator() *SchemaGenerator

GetSchemaGenerator returns the schema generator for advanced usage

func (*Generator) GetSpec

func (g *Generator) GetSpec() *OpenAPISpec

GetSpec returns the current specification

func (*Generator) GetStatistics

func (g *Generator) GetStatistics() Statistics

GetStatistics returns statistics about the current documentation

func (*Generator) ListEndpoints

func (g *Generator) ListEndpoints() map[string][]string

ListEndpoints returns all registered endpoints

func (*Generator) Merge

func (g *Generator) Merge(other *Generator) error

Merge merges another generator into this one

func (*Generator) RemoveEndpoint

func (g *Generator) RemoveEndpoint(method, path string)

RemoveEndpoint removes an endpoint from the documentation

func (*Generator) Reset

func (g *Generator) Reset()

Reset clears all endpoints and resets the specification

func (*Generator) SetExternalDocs

func (g *Generator) SetExternalDocs(docs ExternalDocumentation)

SetExternalDocs sets external documentation

func (*Generator) UpdateInfo

func (g *Generator) UpdateInfo(info Info)

UpdateInfo updates the API information

type Header struct {
	Description     string               `json:"description,omitempty" yaml:"description,omitempty"`
	Required        bool                 `json:"required,omitempty" yaml:"required,omitempty"`
	Deprecated      bool                 `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	AllowEmptyValue bool                 `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
	Style           string               `json:"style,omitempty" yaml:"style,omitempty"`
	Explode         *bool                `json:"explode,omitempty" yaml:"explode,omitempty"`
	AllowReserved   bool                 `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"`
	Schema          *Schema              `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example         any                  `json:"example,omitempty" yaml:"example,omitempty"`
	Examples        map[string]Example   `json:"examples,omitempty" yaml:"examples,omitempty"`
	Content         map[string]MediaType `json:"content,omitempty" yaml:"content,omitempty"`
}

Header follows the structure of the Parameter Object

type HeaderInfo

type HeaderInfo struct {
	Description string
	Type        reflect.Type
	Example     any
	Schema      *Schema
}

HeaderInfo contains information about a response header

type Info

type Info struct {
	Title          string   `json:"title" yaml:"title"`
	Description    string   `json:"description,omitempty" yaml:"description,omitempty"`
	TermsOfService string   `json:"termsOfService,omitempty" yaml:"termsOfService,omitempty"`
	Contact        *Contact `json:"contact,omitempty" yaml:"contact,omitempty"`
	License        *License `json:"license,omitempty" yaml:"license,omitempty"`
	Version        string   `json:"version" yaml:"version"`
}

Info provides metadata about the API

type License

type License struct {
	Name string `json:"name" yaml:"name"`
	URL  string `json:"url,omitempty" yaml:"url,omitempty"`
}

License information for the exposed API

type Link struct {
	OperationRef string         `json:"operationRef,omitempty" yaml:"operationRef,omitempty"`
	OperationID  string         `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Parameters   map[string]any `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody  any            `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
	Description  string         `json:"description,omitempty" yaml:"description,omitempty"`
	Server       *Server        `json:"server,omitempty" yaml:"server,omitempty"`
}

Link represents a possible design-time link for a response

type MediaType

type MediaType struct {
	Schema   *Schema             `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example  any                 `json:"example,omitempty" yaml:"example,omitempty"`
	Examples map[string]Example  `json:"examples,omitempty" yaml:"examples,omitempty"`
	Encoding map[string]Encoding `json:"encoding,omitempty" yaml:"encoding,omitempty"`
}

MediaType provides schema and examples for the media type identified by its key

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string            `json:"authorizationUrl,omitempty" yaml:"authorizationUrl,omitempty"`
	TokenURL         string            `json:"tokenUrl,omitempty" yaml:"tokenUrl,omitempty"`
	RefreshURL       string            `json:"refreshUrl,omitempty" yaml:"refreshUrl,omitempty"`
	Scopes           map[string]string `json:"scopes" yaml:"scopes"`
}

OAuthFlow configuration details for a supported OAuth Flow

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow `json:"implicit,omitempty" yaml:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty" yaml:"password,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty" yaml:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty" yaml:"authorizationCode,omitempty"`
}

OAuthFlows allows configuration of the supported OAuth Flows

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI      string                 `json:"openapi" yaml:"openapi"`
	Info         Info                   `json:"info" yaml:"info"`
	Servers      []Server               `json:"servers,omitempty" yaml:"servers,omitempty"`
	Paths        map[string]PathItem    `json:"paths" yaml:"paths"`
	Components   *Components            `json:"components,omitempty" yaml:"components,omitempty"`
	Security     []SecurityRequirement  `json:"security,omitempty" yaml:"security,omitempty"`
	Tags         []Tag                  `json:"tags,omitempty" yaml:"tags,omitempty"`
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

OpenAPISpec represents the root OpenAPI 3.0 specification

func NewOpenAPISpec

func NewOpenAPISpec() *OpenAPISpec

NewOpenAPISpec creates a new OpenAPI specification with default values

func (*OpenAPISpec) ToJSON

func (spec *OpenAPISpec) ToJSON() ([]byte, error)

ToJSON converts the OpenAPI spec to JSON

type Operation

type Operation struct {
	Tags         []string               `json:"tags,omitempty" yaml:"tags,omitempty"`
	Summary      string                 `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description  string                 `json:"description,omitempty" yaml:"description,omitempty"`
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
	OperationID  string                 `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Parameters   []Parameter            `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody  *RequestBody           `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
	Responses    map[string]Response    `json:"responses" yaml:"responses"`
	Callbacks    map[string]Callback    `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`
	Deprecated   bool                   `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	Security     []SecurityRequirement  `json:"security,omitempty" yaml:"security,omitempty"`
	Servers      []Server               `json:"servers,omitempty" yaml:"servers,omitempty"`
}

Operation describes a single API operation on a path

type PaginatedResponse

type PaginatedResponse struct {
	Data       any `json:"data" description:"Response data"`
	Page       int `json:"page" description:"Current page number"`
	PerPage    int `json:"per_page" description:"Items per page"`
	Total      int `json:"total" description:"Total number of items"`
	TotalPages int `json:"total_pages" description:"Total number of pages"`
}

PaginatedResponse represents a paginated response

type Parameter

type Parameter struct {
	Name            string               `json:"name" yaml:"name"`
	In              string               `json:"in" yaml:"in"`
	Description     string               `json:"description,omitempty" yaml:"description,omitempty"`
	Required        bool                 `json:"required,omitempty" yaml:"required,omitempty"`
	Deprecated      bool                 `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	AllowEmptyValue bool                 `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
	Style           string               `json:"style,omitempty" yaml:"style,omitempty"`
	Explode         *bool                `json:"explode,omitempty" yaml:"explode,omitempty"`
	AllowReserved   bool                 `json:"allowReserved,omitempty" yaml:"allowReserved,omitempty"`
	Schema          *Schema              `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example         any                  `json:"example,omitempty" yaml:"example,omitempty"`
	Examples        map[string]Example   `json:"examples,omitempty" yaml:"examples,omitempty"`
	Content         map[string]MediaType `json:"content,omitempty" yaml:"content,omitempty"`
}

Parameter describes a single operation parameter

type ParameterInfo

type ParameterInfo struct {
	Name        string
	Description string
	Required    bool
	Type        reflect.Type
	Example     any
	Schema      *Schema
}

ParameterInfo contains information about a parameter

func FilterParams

func FilterParams() []ParameterInfo

FilterParams returns common filtering parameters

func PaginationParams

func PaginationParams() []ParameterInfo

PaginationParams returns common pagination parameters

type PathItem

type PathItem struct {
	Ref         string      `json:"$ref,omitempty" yaml:"$ref,omitempty"`
	Summary     string      `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description string      `json:"description,omitempty" yaml:"description,omitempty"`
	Get         *Operation  `json:"get,omitempty" yaml:"get,omitempty"`
	Put         *Operation  `json:"put,omitempty" yaml:"put,omitempty"`
	Post        *Operation  `json:"post,omitempty" yaml:"post,omitempty"`
	Delete      *Operation  `json:"delete,omitempty" yaml:"delete,omitempty"`
	Options     *Operation  `json:"options,omitempty" yaml:"options,omitempty"`
	Head        *Operation  `json:"head,omitempty" yaml:"head,omitempty"`
	Patch       *Operation  `json:"patch,omitempty" yaml:"patch,omitempty"`
	Trace       *Operation  `json:"trace,omitempty" yaml:"trace,omitempty"`
	Servers     []Server    `json:"servers,omitempty" yaml:"servers,omitempty"`
	Parameters  []Parameter `json:"parameters,omitempty" yaml:"parameters,omitempty"`
}

PathItem describes the operations available on a single path

type RequestBody

type RequestBody struct {
	Description string               `json:"description,omitempty" yaml:"description,omitempty"`
	Content     map[string]MediaType `json:"content" yaml:"content"`
	Required    bool                 `json:"required,omitempty" yaml:"required,omitempty"`
}

RequestBody describes a single request body

type RequestBodyInfo

type RequestBodyInfo struct {
	Description  string
	Required     bool
	ContentTypes []string
	Type         reflect.Type
	Example      any
	Schema       *Schema
}

RequestBodyInfo contains information about request body

type Response

type Response struct {
	Description string               `json:"description" yaml:"description"`
	Headers     map[string]Header    `json:"headers,omitempty" yaml:"headers,omitempty"`
	Content     map[string]MediaType `json:"content,omitempty" yaml:"content,omitempty"`
	Links       map[string]Link      `json:"links,omitempty" yaml:"links,omitempty"`
}

Response describes a single response from an API Operation

type ResponseInfo

type ResponseInfo struct {
	Description  string
	ContentTypes []string
	Type         reflect.Type
	Example      any
	Schema       *Schema
	Headers      map[string]HeaderInfo
}

ResponseInfo contains information about a response

type Schema

type Schema struct {
	// Core schema properties
	Type                 string            `json:"type,omitempty" yaml:"type,omitempty"`
	AllOf                []Schema          `json:"allOf,omitempty" yaml:"allOf,omitempty"`
	OneOf                []Schema          `json:"oneOf,omitempty" yaml:"oneOf,omitempty"`
	AnyOf                []Schema          `json:"anyOf,omitempty" yaml:"anyOf,omitempty"`
	Not                  *Schema           `json:"not,omitempty" yaml:"not,omitempty"`
	Items                *Schema           `json:"items,omitempty" yaml:"items,omitempty"`
	Properties           map[string]Schema `json:"properties,omitempty" yaml:"properties,omitempty"`
	AdditionalProperties any               `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty"`
	Description          string            `json:"description,omitempty" yaml:"description,omitempty"`
	Format               string            `json:"format,omitempty" yaml:"format,omitempty"`
	Default              any               `json:"default,omitempty" yaml:"default,omitempty"`

	// Validation properties
	MultipleOf       *float64 `json:"multipleOf,omitempty" yaml:"multipleOf,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty" yaml:"maximum,omitempty"`
	ExclusiveMaximum *bool    `json:"exclusiveMaximum,omitempty" yaml:"exclusiveMaximum,omitempty"`
	Minimum          *float64 `json:"minimum,omitempty" yaml:"minimum,omitempty"`
	ExclusiveMinimum *bool    `json:"exclusiveMinimum,omitempty" yaml:"exclusiveMinimum,omitempty"`
	MaxLength        *int     `json:"maxLength,omitempty" yaml:"maxLength,omitempty"`
	MinLength        *int     `json:"minLength,omitempty" yaml:"minLength,omitempty"`
	Pattern          string   `json:"pattern,omitempty" yaml:"pattern,omitempty"`
	MaxItems         *int     `json:"maxItems,omitempty" yaml:"maxItems,omitempty"`
	MinItems         *int     `json:"minItems,omitempty" yaml:"minItems,omitempty"`
	UniqueItems      *bool    `json:"uniqueItems,omitempty" yaml:"uniqueItems,omitempty"`
	MaxProperties    *int     `json:"maxProperties,omitempty" yaml:"maxProperties,omitempty"`
	MinProperties    *int     `json:"minProperties,omitempty" yaml:"minProperties,omitempty"`
	Required         []string `json:"required,omitempty" yaml:"required,omitempty"`
	Enum             []any    `json:"enum,omitempty" yaml:"enum,omitempty"`

	// OpenAPI-specific properties
	Title        string                 `json:"title,omitempty" yaml:"title,omitempty"`
	Example      any                    `json:"example,omitempty" yaml:"example,omitempty"`
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
	Deprecated   *bool                  `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	ReadOnly     *bool                  `json:"readOnly,omitempty" yaml:"readOnly,omitempty"`
	WriteOnly    *bool                  `json:"writeOnly,omitempty" yaml:"writeOnly,omitempty"`
	XML          *XML                   `json:"xml,omitempty" yaml:"xml,omitempty"`

	// Reference
	Ref string `json:"$ref,omitempty" yaml:"$ref,omitempty"`
}

Schema represents a schema object

type SchemaGenerator

type SchemaGenerator struct {
	// contains filtered or unexported fields
}

SchemaGenerator handles the generation of OpenAPI schemas from Go types

func NewSchemaGenerator

func NewSchemaGenerator() *SchemaGenerator

NewSchemaGenerator creates a new schema generator

func (*SchemaGenerator) GenerateSchema

func (sg *SchemaGenerator) GenerateSchema(t reflect.Type) Schema

GenerateSchema generates an OpenAPI schema from a Go type

func (*SchemaGenerator) GenerateSchemaFromValue

func (sg *SchemaGenerator) GenerateSchemaFromValue(v any) Schema

GenerateSchemaFromValue generates a schema from a value (useful for examples)

func (*SchemaGenerator) GenerateSchemaWithName

func (sg *SchemaGenerator) GenerateSchemaWithName(t reflect.Type, name string) Schema

GenerateSchemaWithName generates an OpenAPI schema with a specific name

func (*SchemaGenerator) GetSchemas

func (sg *SchemaGenerator) GetSchemas() map[string]Schema

GetSchemas returns all generated schemas

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement lists the required security schemes to execute this operation

type SecurityScheme

type SecurityScheme struct {
	Type             string      `json:"type" yaml:"type"`
	Description      string      `json:"description,omitempty" yaml:"description,omitempty"`
	Name             string      `json:"name,omitempty" yaml:"name,omitempty"`
	In               string      `json:"in,omitempty" yaml:"in,omitempty"`
	Scheme           string      `json:"scheme,omitempty" yaml:"scheme,omitempty"`
	BearerFormat     string      `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"`
	Flows            *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"`
	OpenIDConnectURL string      `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"`
}

SecurityScheme defines a security scheme that can be used by the operations

type Server

type Server struct {
	URL         string                    `json:"url" yaml:"url"`
	Description string                    `json:"description,omitempty" yaml:"description,omitempty"`
	Variables   map[string]ServerVariable `json:"variables,omitempty" yaml:"variables,omitempty"`
}

Server represents a server

type ServerVariable

type ServerVariable struct {
	Enum        []string `json:"enum,omitempty" yaml:"enum,omitempty"`
	Default     string   `json:"default" yaml:"default"`
	Description string   `json:"description,omitempty" yaml:"description,omitempty"`
}

ServerVariable represents a server variable for server URL template substitution

type Statistics

type Statistics struct {
	TotalEndpoints    int
	TotalSchemas      int
	EndpointsByMethod map[string]int
	EndpointsByTag    map[string]int
}

Statistics returns statistics about the generated documentation

type SuccessResponse

type SuccessResponse struct {
	Message string `json:"message" description:"Success message"`
	Data    any    `json:"data,omitempty" description:"Response data"`
}

SuccessResponse represents a standard success response

type Tag

type Tag struct {
	Name         string                 `json:"name" yaml:"name"`
	Description  string                 `json:"description,omitempty" yaml:"description,omitempty"`
	ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

Tag adds metadata to a single tag that is used by the Operation Object

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer handles writing OpenAPI documentation to various formats

func NewWriter

func NewWriter(generator *Generator) *Writer

NewWriter creates a new documentation writer

func (*Writer) CleanOutputDir

func (w *Writer) CleanOutputDir() error

CleanOutputDir removes all generated files

func (*Writer) GenerateMarkdownDocs

func (w *Writer) GenerateMarkdownDocs() error

GenerateMarkdownDocs generates markdown documentation

func (*Writer) GetGeneratedFiles

func (w *Writer) GetGeneratedFiles() []string

GetGeneratedFiles returns a list of files that would be generated

func (*Writer) WatchAndRegenerate

func (w *Writer) WatchAndRegenerate(interval time.Duration, callback func() error)

WatchAndRegenerate watches for changes and regenerates documentation

func (*Writer) WriteFiles

func (w *Writer) WriteFiles() error

WriteFiles generates and writes all configured output formats

func (*Writer) WriteHTML

func (w *Writer) WriteHTML(spec *OpenAPISpec) error

WriteHTML writes the specification as HTML with Swagger UI

func (*Writer) WriteJSON

func (w *Writer) WriteJSON(spec *OpenAPISpec) error

WriteJSON writes the specification as JSON

func (*Writer) WriteToFile

func (w *Writer) WriteToFile(filename string, format string) error

WriteToFile writes the specification to a specific file

func (*Writer) WriteYAML

func (w *Writer) WriteYAML(spec *OpenAPISpec) error

WriteYAML writes the specification as YAML

type XML

type XML struct {
	Name      string `json:"name,omitempty" yaml:"name,omitempty"`
	Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"`
	Prefix    string `json:"prefix,omitempty" yaml:"prefix,omitempty"`
	Attribute bool   `json:"attribute,omitempty" yaml:"attribute,omitempty"`
	Wrapped   bool   `json:"wrapped,omitempty" yaml:"wrapped,omitempty"`
}

XML metadata object

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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