fiberopenapi

package module
v0.3.6 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 9 Imported by: 0

README

fiberopenapi

Go Reference Go Report Card

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

Features

  • ⚡ Seamless Integration — Works with your existing Fiber 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
  • 🚀 Zero Overhead — Minimal performance impact on your API

Installation

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

Quick Start

package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/oaswrap/spec/adapter/fiberopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	app := fiber.New()

	// Create a new OpenAPI router
	r := fiberopenapi.NewRouter(app,
		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 := app.Listen(":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 `params:"id" required:"true"`
}

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

func AuthMiddleware(c *fiber.Ctx) error {
	authHeader := c.Get("Authorization")
	if authHeader != "" && authHeader == "Bearer example-token" {
		return c.Next()
	}
	return c.Status(401).JSON(map[string]string{"error": "Unauthorized"})
}

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

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

Documentation Features

Built-in Endpoints

When you create a fiberopenapi 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 := fiberopenapi.NewRouter(c,
	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 := fiberopenapi.NewRouter(c,
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithScalar(), // Use Scalar as the documentation UI
)
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"`
}

For more struct tag options, see the swaggest/openapi-go.

Examples

Check out complete examples in the main repository:

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. Use Validation Tags — Leverage struct tags for request validation documentation
  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 for errors at OpenAPI router initialization.
	Validate() error

	// GenerateSchema generates the OpenAPI schema in the specified format.
	GenerateSchema(format ...string) ([]byte, error)
	// MarshalYAML marshals the OpenAPI schema to YAML format.
	MarshalYAML() ([]byte, error)
	// MarshalJSON marshals the OpenAPI schema to JSON format.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the OpenAPI schema to a file.
	WriteSchemaTo(filePath string) error
}

Generator defines the interface for generating OpenAPI schemas.

func NewGenerator

func NewGenerator(r fiber.Router, opts ...option.OpenAPIOption) Generator

NewGenerator creates a new OpenAPI generator with the specified Fiber router and options.

It initializes the OpenAPI router and sets up the necessary routes for OpenAPI documentation.

func NewRouter

func NewRouter(r fiber.Router, opts ...option.OpenAPIOption) Generator

NewRouter creates a new OpenAPI router with the specified Fiber router and options.

It initializes the OpenAPI generator and sets up the necessary routes for OpenAPI documentation.

type Route

type Route interface {
	// Name sets the name for the route.
	Name(name string) Route
	// With applies the given options to the route.
	With(opts ...option.OperationOption) Route
}

Route represents a single route in the OpenAPI specification.

type Router

type Router interface {
	// Use applies middleware to the router.
	Use(args ...any) Router

	// Get registers a GET route.
	Get(path string, handler ...fiber.Handler) Route
	// Head registers a HEAD route.
	Head(path string, handler ...fiber.Handler) Route
	// Post registers a POST route.
	Post(path string, handler ...fiber.Handler) Route
	// Put registers a PUT route.
	Put(path string, handler ...fiber.Handler) Route
	// Patch registers a PATCH route.
	Patch(path string, handler ...fiber.Handler) Route
	// Delete registers a DELETE route.
	Delete(path string, handler ...fiber.Handler) Route
	// Connect registers a CONNECT route.
	Connect(path string, handler ...fiber.Handler) Route
	// Options registers an OPTIONS route.
	Options(path string, handler ...fiber.Handler) Route
	// Trace registers a TRACE route.
	Trace(path string, handler ...fiber.Handler) Route

	// Add registers a route with the specified method and path.
	Add(method, path string, handler ...fiber.Handler) Route
	// Static serves static files from the specified root directory.
	Static(prefix, root string, config ...fiber.Static) Router

	// Group creates a new sub-router with the specified prefix and handlers.
	// The prefix is prepended to all routes in the sub-router.
	Group(prefix string, handlers ...fiber.Handler) Router

	// Route creates a new sub-router with the specified prefix and applies options.
	Route(prefix string, fn func(router Router), opts ...option.GroupOption) Router

	// With applies options to the router.
	// This allows you to configure tags, security, and visibility for the routes.
	With(opts ...option.GroupOption) Router
}

Router defines the interface for an OpenAPI router.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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