spec

package module
v0.2.0-dev.2 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 18 Imported by: 19

README ยถ

oaswrap/spec

CI Go Reference Go Report Card License

A lightweight, framework-agnostic OpenAPI 3.x specification builder for Go that gives you complete control over your API documentation without vendor lock-in.

Why oaswrap/spec?

  • ๐ŸŽฏ Framework Agnostic โ€” Works with any Go web framework or as a standalone tool
  • โšก Zero Dependencies โ€” Powered by swaggest/openapi-go with minimal overhead
  • ๐Ÿ”ง Programmatic Control โ€” Build specs in pure Go code with full type safety
  • ๐Ÿš€ Adapter Ecosystem โ€” Seamless integration with popular frameworks via dedicated adapters
  • ๐Ÿ“ CI/CD Ready โ€” Generate specs at build time for documentation pipelines

Quick Start

Installation
go get github.com/oaswrap/spec
Basic Usage (Standalone)

Perfect for generating OpenAPI specs in CI/CD, build scripts, or documentation tools:

package main

import (
	"log"

	"github.com/oaswrap/spec"
	"github.com/oaswrap/spec/option"
)

func main() {
	// Create a new OpenAPI router
	r := spec.NewRouter(
		option.WithTitle("My API"),
		option.WithVersion("1.0.0"),
		option.WithServer("https://api.example.com"),
	)

	// Add routes
	v1 := r.Group("/api/v1")
	
	v1.Post("/login",
		option.Summary("User login"),
		option.Request(new(LoginRequest)),
		option.Response(200, new(LoginResponse)),
	)

	v1.Get("/users/{id}",
		option.Summary("Get user by ID"),
		option.Request(new(GetUserRequest)),
		option.Response(200, new(User)),
	)

	// Generate OpenAPI spec
	if err := r.WriteSchemaTo("openapi.yaml"); err != nil {
		log.Fatal(err)
	}

	log.Println("โœ… OpenAPI spec generated at openapi.yaml")
}

type LoginRequest struct {
	Username string `json:"username" required:"true"`
	Password string `json:"password" required:"true"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

type GetUserRequest struct {
	ID string `path:"id" required:"true"`
}

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

๐Ÿ“– View the generated spec on Rest.Wiki

Framework Integration

For seamless HTTP server integration, use one of our framework adapters. Each adapter has its own repository with complete examples and documentation.

Available Adapters
Framework Adapter Package
Gin ginopenapi
Echo echoopenapi
Fiber fiberopenapi

Each adapter provides:

  • Automatic spec generation from your routes
  • Built-in Swagger UI documentation
  • JSON/YAML spec endpoints
  • Inline OpenAPI options with route definitions

Visit the individual adapter repositories for framework-specific examples and detailed integration guides.

Configuration Options

The option package provides comprehensive OpenAPI configuration:

Basic Information
option.WithOpenAPIVersion("3.0.3") // Specify OpenAPI version (default is "3.0.3")
option.WithTitle("My API")
option.WithDescription("API description")
option.WithVersion("1.2.3")
option.WithContact(openapi.Contact{
	Name:  "Support Team",
	URL:   "https://support.example.com",
	Email: "support@example.com",
})
option.WithLicense(openapi.License{
	Name: "MIT License",
	URL:  "https://opensource.org/licenses/MIT",
})
option.WithExternalDocs("https://docs.example.com", "API Documentation")
option.WithTags(
	openapi.Tag{
		Name:        "User Management",
		Description: "Operations related to user management",
	},
	openapi.Tag{
		Name:        "Authentication",
		Description: "Authentication related operations",
	},
)
Servers
option.WithServer("https://api.example.com")
option.WithServer("https://api-example.com/{version}",
	option.ServerDescription("Production Server"),
	option.ServerVariables(map[string]openapi.ServerVariable{
		"version": {
			Default:     "v1",
			Enum:        []string{"v1", "v2"},
			Description: "API version",
		},
	}),
)
Security Schemes
// Bearer token
option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer"))

// API Key
option.WithSecurity("apiKey", option.SecurityAPIKey("X-API-Key", "header"))

// OAuth2
option.WithSecurity("oauth2", option.SecurityOAuth2(
	openapi.OAuthFlows{
		Implicit: &openapi.OAuthFlowsImplicit{
			AuthorizationURL: "https://auth.example.com/authorize",
			Scopes: map[string]string{
				"read":  "Read access",
				"write": "Write access",
			},
		},
	},
))
Route Documentation
option.OperationID("getUserByID") // Specify unique operation ID
option.Summary("Short description") // Brief summary of the operation
option.Description("Detailed description") // Full description of the operation
option.Tags("User Management", "Authentication") // Group operations by tags
option.Request(new(RequestModel)) // Define request body model
option.Response(200, new(ResponseModel), // Define response model
	option.ContentDescription("Successful response"), // Add description for response
	option.ContentType("application/json"), // Specify content type
	option.ContentDefault(true), // Mark as default response
)
option.Security("bearerAuth") // Apply security scheme to the route
option.Deprecated() // Mark route as deprecated
option.Hidden()     // Hide route from OpenAPI spec

Parameters (path, query, headers) are defined using struct tags in your request models:

type GetUserRequest struct {
	ID     string `path:"id" required:"true" description:"User identifier"`
	Limit  int    `query:"limit" description:"Maximum number of results"`
	APIKey string `header:"X-API-Key" description:"API authentication key"`
}
Group-Level Configuration

Apply settings to all routes within a group:

// Apply tags, security, and other settings to all routes in the group
adminGroup := r.Group("/admin",
	option.GroupTags("Administration"),
	option.GroupSecurity("bearerAuth"),
	option.GroupDeprecated(), // Mark all routes as deprecated
)

// Hide internal routes from documentation
internalGroup := r.Group("/internal",
	option.GroupHidden(), // Exclude from OpenAPI spec
)

Use Cases

โœ… Use spec standalone when you:
  • Generate OpenAPI files at build time
  • Integrate with CI/CD pipelines
  • Build custom documentation tools
  • Need static spec generation
  • Want framework independence
โœ… Use framework adapters when you:
  • Want automatic spec generation from routes
  • Need built-in documentation UI
  • Prefer inline OpenAPI configuration
  • Want live spec endpoints

Advanced Features

Rich Schema Documentation
// Use struct tags to generate detailed OpenAPI schemas
type CreateUserRequest struct {
	Name     string   `json:"name" required:"true" minLength:"2" maxLength:"50"`
	Email    string   `json:"email" required:"true" format:"email"`
	Age      int      `json:"age" minimum:"18" maximum:"120"`
	Tags     []string `json:"tags" maxItems:"10"`
}

For comprehensive struct tag documentation and advanced schema features, see the swaggest/openapi-go features guide and swaggest/jsonschema-go field tags.

Generic Response Types
type APIResponse[T any] struct {
	Success   bool   `json:"success"`
	Data      T      `json:"data,omitempty"`
	Error     string `json:"error,omitempty"`
	Timestamp string `json:"timestamp"`
}

// Usage
option.Response(200, new(APIResponse[User]))
option.Response(200, new(APIResponse[[]Product]))

Examples

Check out the examples/ directory for complete working examples:

  • Basic โ€” Standalone spec generation
  • Petstore โ€” Full Petstore API example with routes and models

API Reference

For complete API documentation, visit pkg.go.dev/github.com/oaswrap/spec.

Key packages:

  • spec โ€” Core router and spec builder
  • option โ€” All configuration options

FAQ

Q: Can I use this with my existing API?
A: Yes! You can either use the standalone version to document existing APIs, or gradually migrate to framework adapters.

Q: How does this compare to swag/swaggo?
A: While swag uses code comments, oaswrap uses pure Go code for type safety and better IDE support. Both approaches have their merits.

Q: Can I customize the generated documentation UI?
A: Framework adapters provide built-in UIs, but you can also serve the spec with any OpenAPI-compatible documentation tool.

Q: Is this production ready?
A: The library is in active development. While the core functionality is solid, consider it beta software. We recommend thorough testing before production use.

Roadmap

  • Chi adapter
  • HTTP adapter
  • Stoplight support
  • Redoc UI support

Contributing

We welcome contributions! Here's how you can help:

  1. ๐Ÿ› Report bugs โ€” Open an issue with reproduction steps
  2. ๐Ÿ’ก Suggest features โ€” Share your ideas for improvements
  3. ๐Ÿ“ Improve docs โ€” Help make our documentation clearer
  4. ๐Ÿ”ง Submit PRs โ€” Fix bugs or add features

Please check our issues and discussions before starting work on new features.

License

MIT License โ€” Created with โค๏ธ by Ahmad Faiz.

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

This section is empty.

Types ยถ

type Generator ยถ

type Generator interface {
	Router

	// Config returns the OpenAPI configuration used by the Generator.
	Config() *specopenapi.Config

	// GenerateSchema generates the OpenAPI schema in the specified format.
	// By default, it generates YAML. Pass "json" to generate JSON instead.
	GenerateSchema(formats ...string) ([]byte, error)

	// MarshalYAML returns the OpenAPI specification marshaled as YAML.
	MarshalYAML() ([]byte, error)

	// MarshalJSON returns the OpenAPI specification marshaled as JSON.
	MarshalJSON() ([]byte, error)

	// Validate checks whether the OpenAPI specification is valid.
	Validate() error

	// WriteSchemaTo writes the OpenAPI schema to a file.
	// The format is inferred from the file extension: ".yaml" for YAML, ".json" for JSON.
	WriteSchemaTo(path string) error
}

Generator defines an interface for building and exporting OpenAPI specifications.

func NewGenerator ยถ

func NewGenerator(opts ...option.OpenAPIOption) Generator

NewGenerator returns a new Generator instance using the given OpenAPI options.

It initializes the OpenAPI reflector and configuration.

func NewRouter ยถ added in v0.1.3

func NewRouter(opts ...option.OpenAPIOption) Generator

NewRouter returns a new Router instance using the given OpenAPI options.

It is equivalent to NewGenerator.

See also: NewGenerator.

type Route ยถ added in v0.1.3

type Route interface {
	// With applies additional operation options to the route.
	With(opts ...option.OperationOption) Route
}

Route represents a single API route in the OpenAPI specification.

type Router ยถ added in v0.1.3

type Router interface {
	// Get registers a GET operation for the given path and options.
	Get(path string, opts ...option.OperationOption) Route

	// Post registers a POST operation for the given path and options.
	Post(path string, opts ...option.OperationOption) Route

	// Put registers a PUT operation for the given path and options.
	Put(path string, opts ...option.OperationOption) Route

	// Delete registers a DELETE operation for the given path and options.
	Delete(path string, opts ...option.OperationOption) Route

	// Patch registers a PATCH operation for the given path and options.
	Patch(path string, opts ...option.OperationOption) Route

	// Options registers an OPTIONS operation for the given path and options.
	Options(path string, opts ...option.OperationOption) Route

	// Head registers a HEAD operation for the given path and options.
	Head(path string, opts ...option.OperationOption) Route

	// Trace registers a TRACE operation for the given path and options.
	Trace(path string, opts ...option.OperationOption) Route

	// Add registers an operation for the given HTTP method, path, and options.
	Add(method, path string, opts ...option.OperationOption) Route

	// Route registers a nested route under the given pattern.
	// The provided function receives a Router to define sub-routes.
	Route(pattern string, fn func(router Router), opts ...option.GroupOption) Router

	// Group creates a new sub-router with the given path prefix and group options.
	Group(pattern string, opts ...option.GroupOption) Router

	// Use applies one or more group options to the router.
	Use(opts ...option.GroupOption) Router
}

Router defines methods for registering API routes and operations in an OpenAPI specification. It lets you describe HTTP methods, paths, and options.

Directories ยถ

Path Synopsis
adapter
chiopenapi module
echoopenapi module
fiberopenapi module
ginopenapi module
httpopenapi module
muxopenapi module
adapters
chiopenapi module
echoopenapi module
fiberopenapi module
ginopenapi module
httpopenapi module
examples
basic command
petstore command
internal
module
specui module
Package option provides functional options for configuring OpenAPI generation, including server setup, group settings, operation options, and reflector behavior.
Package option provides functional options for configuring OpenAPI generation, including server setup, group settings, operation options, and reflector behavior.
pkg
dto

Jump to

Keyboard shortcuts

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