echoopenapi

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 9 Imported by: 0

README ยถ

echoopenapi

Go Reference Go Report Card

A lightweight adapter for the Echo web framework that automatically generates OpenAPI 3.x specifications from your routes using oaswrap/spec.

Note: This adapter is for Echo v4. For Echo v5, use echov5openapi.

Features

  • โšก Seamless Integration โ€” Works with your existing Echo routes and handlers
  • ๐Ÿ“ Automatic Documentation โ€” Generate OpenAPI specs from route definitions and struct tags
  • ๐ŸŽฏ Type Safety โ€” Full Go type safety for OpenAPI configuration
  • ๐Ÿ”ง Multiple UI Options โ€” Swagger UI, Stoplight Elements, ReDoc, Scalar or RapiDoc served automatically at /docs
  • ๐Ÿ“„ YAML Export โ€” OpenAPI spec available at /docs/openapi.yaml
  • ๐Ÿš€ Low Overhead โ€” Minimal runtime work beyond route registration and docs serving

Installation

go get github.com/oaswrap/spec/adapter/echoopenapi

Quick Start

package main

import (
	"log"

	"github.com/labstack/echo/v4"
	"github.com/oaswrap/spec/adapter/echoopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	e := echo.New()

	// Create a new OpenAPI router
	r := echoopenapi.NewRouter(e,
		option.WithTitle("My API"),
		option.WithVersion("1.0.0"),
		option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("Bearer")),
	)
	// Add routes
	v1 := r.Group("/api/v1")

	v1.POST("/login", LoginHandler).With(
		option.Summary("User login"),
		option.Request(new(LoginRequest)),
		option.Response(200, new(LoginResponse)),
	)

	auth := v1.Group("", AuthMiddleware).With(
		option.GroupSecurity("bearerAuth"),
	)
	auth.GET("/users/:id", GetUserHandler).With(
		option.Summary("Get user by ID"),
		option.Request(new(GetUserRequest)),
		option.Response(200, new(User)),
	)

	log.Printf("๐Ÿš€ OpenAPI docs available at: %s", "http://localhost:3000/docs")

	if err := e.Start(":3000"); err != nil {
		log.Fatal(err)
	}
}

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 `param:"id" required:"true"`
}

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

func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		// Simulate authentication logic
		authHeader := c.Request().Header.Get("Authorization")
		if authHeader != "" && authHeader == "Bearer example-token" {
			return next(c)
		}
		return c.JSON(401, map[string]string{"error": "Unauthorized"})
	}
}

func LoginHandler(c echo.Context) error {
	var req LoginRequest
	if err := c.Bind(&req); err != nil {
		return c.JSON(400, map[string]string{"error": "Invalid request"})
	}
	// Simulate login logic
	return c.JSON(200, LoginResponse{Token: "example-token"})
}

func GetUserHandler(c echo.Context) error {
	var req GetUserRequest
	if err := c.Bind(&req); err != nil {
		return c.JSON(400, map[string]string{"error": "Invalid request"})
	}
	// Simulate fetching user by ID
	user := User{ID: req.ID, Name: "John Doe"}
	return c.JSON(200, user)
}

Documentation Features

Built-in Endpoints

When you create a echoopenapi router, the following endpoints are automatically available:

  • /docs โ€” Interactive UI documentation
  • /docs/openapi.yaml โ€” Raw OpenAPI specification in YAML format

If you want to disable the built-in UI, you can do so by passing option.WithDisableDocs() when creating the router:

r := echoopenapi.NewRouter(e,
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithDisableDocs(),
)
Supported Documentation UIs

Choose from multiple UI options, powered by oaswrap/spec-ui:

  • Stoplight Elements โ€” Modern, clean design (default)
  • Swagger UI โ€” Classic interface with try-it functionality
  • ReDoc โ€” Three-panel responsive layout
  • Scalar โ€” Beautiful and fast interface
  • RapiDoc โ€” Highly customizable
r := echoopenapi.NewRouter(e,
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithScalar(), // Use Scalar as the documentation UI
)
Embed Mode (Local Assets)

By default, UI providers use CDN assets to keep binaries small.

To serve embedded assets (offline mode), use option.WithUIOption(...) with the provider emb package directly:

import (
    stoplightemb "github.com/oaswrap/spec-ui/stoplightemb"
)

// example:
option.WithUIOption(stoplightemb.WithUI())
Rich Schema Documentation

Use struct tags to generate detailed OpenAPI schemas. Note: These tags are used only for OpenAPI spec generation and documentation - they do not perform actual request validation.

type CreateProductRequest struct {
	Name        string   `json:"name" required:"true" minLength:"1" maxLength:"100"`
	Description string   `json:"description" maxLength:"500"`
	Price       float64  `json:"price" required:"true" minimum:"0" maximum:"999999.99"`
	Category    string   `json:"category" required:"true" enum:"electronics,books,clothing"`
	Tags        []string `json:"tags" maxItems:"10"`
	InStock     bool     `json:"in_stock" default:"true"`
}

Supported tags are implemented by oaswrap/spec directly. Common request tags include json, form, path, query, header, and cookie; common schema tags include description, format, default, example, enum, minimum, maximum, minLength, maxLength, minItems, maxItems, nullable, deprecated, readOnly, and writeOnly. See the root Reflection Tags section for the complete list.

Example

Check out the examples directory for more complete implementations and use cases.

Best Practices

  1. Organize with Tags โ€” Group related operations using option.Tags()
  2. Document Everything โ€” Use option.Summary() and option.Description() for all routes
  3. Define Error Responses โ€” Include common error responses (400, 401, 404, 500)
  4. Document Schema Constraints โ€” Use reflection tags to describe OpenAPI schema constraints; keep runtime validation in handlers or middleware
  5. Security First โ€” Define and apply appropriate security schemes
  6. Version Your API โ€” Use route groups for API versioning (/api/v1, /api/v2)

API Reference

Contributing

We welcome contributions! Please open issues and PRs at the main oaswrap/spec repository.

License

MIT

Documentation ยถ

Index ยถ

Constants ยถ

This section is empty.

Variables ยถ

This section is empty.

Functions ยถ

This section is empty.

Types ยถ

type Generator ยถ

type Generator interface {
	Router

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

	// ValidateReport validates the schema and returns all findings.
	ValidateReport() error

	// GenerateSchema generates the OpenAPI schema.
	// Defaults to YAML. Pass "json" to generate JSON.
	GenerateSchema(format ...string) ([]byte, error)

	// MarshalYAML marshals the OpenAPI schema to YAML.
	MarshalYAML() ([]byte, error)

	// MarshalJSON marshals the OpenAPI schema to JSON.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the schema to the given file.
	// The format is inferred from the file extension.
	WriteSchemaTo(filepath string) error
}

Generator defines an Echo-compatible OpenAPI generator.

It combines routing and OpenAPI schema generation.

func NewGenerator ยถ

func NewGenerator(e *echo.Echo, opts ...option.OpenAPIOption) Generator

NewGenerator creates a new OpenAPI generator with the provided Echo instance and options.

It initializes the OpenAPI configuration and sets up the necessary routes for serving.

func NewRouter ยถ

func NewRouter(e *echo.Echo, opts ...option.OpenAPIOption) Generator

NewRouter creates a new OpenAPI router with the provided Echo instance and options.

It initializes the OpenAPI configuration and sets up the necessary routes for serving.

type Route ยถ

type Route interface {
	// Method returns the HTTP method (GET, POST, etc.).
	Method() string

	// Path returns the route path.
	Path() string

	// Name returns the route name.
	Name() string

	// With applies OpenAPI operation options to this route.
	With(opts ...option.OperationOption) Route
}

Route represents a single Echo route with OpenAPI metadata.

type Router ยถ

type Router interface {
	// GET registers a new GET route.
	GET(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// POST registers a new POST route.
	POST(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// PUT registers a new PUT route.
	PUT(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// DELETE registers a new DELETE route.
	DELETE(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// PATCH registers a new PATCH route.
	PATCH(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// HEAD registers a new HEAD route.
	HEAD(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// OPTIONS registers a new OPTIONS route.
	OPTIONS(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// TRACE registers a new TRACE route.
	TRACE(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// CONNECT registers a new CONNECT route.
	// CONNECT operations are emitted only for OpenAPI 3.2.0.
	CONNECT(path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// Add registers a new route with the given method, path, and handler.
	Add(method, path string, handler echo.HandlerFunc, m ...echo.MiddlewareFunc) Route

	// Group creates a new sub-group with the given prefix and middleware.
	Group(prefix string, m ...echo.MiddlewareFunc) Router

	// Use adds global middleware.
	Use(m ...echo.MiddlewareFunc) Router

	// File serves a single static file.
	File(path, file string)

	// FileFS serves a static file from the given filesystem.
	FileFS(path, file string, fs fs.FS, m ...echo.MiddlewareFunc)

	// Static serves static files from a directory under the given prefix.
	Static(prefix, root string)

	// StaticFS serves static files from the given filesystem.
	StaticFS(prefix string, fs fs.FS)

	// With applies OpenAPI group options to this router.
	With(opts ...option.GroupOption) Router
}

Router defines an OpenAPI-aware Echo router.

It wraps Echo routes and supports OpenAPI metadata.

Jump to

Keyboard shortcuts

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