fiberopenapi

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2025 License: MIT Imports: 16 Imported by: 1

README

Fiber OpenAPI

Fiber OpenAPI is an OpenAPI documentation generator for Fiber applications. It wraps Fiber’s router and provides methods to define OpenAPI specifications, security schemes, and serve a Swagger UI.

Features

  • Define OpenAPI documentation for your Fiber routes.
  • Support for security schemes, including API keys, HTTP Bearer authentication, and OAuth 2.0.
  • Customizable OpenAPI configuration options.
  • Seamless integration with Fiber’s routing system.
  • Validate your OpenAPI configuration at startup.
  • Leverage struct tags to generate OpenAPI schemas for request and response types.
  • Serve OpenAPI JSON and an interactive Swagger UI out of the box.

Installation

Add the package to your Go project:

go get github.com/afkdevs/fiber-openapi

Usage

Create a new router, configure your OpenAPI settings, and define your routes. Below is a simple example:

package main

import (
	fiberopenapi "github.com/afkdevs/fiber-openapi"
	"github.com/afkdevs/fiber-openapi/option"
	"github.com/gofiber/fiber/v2"
)

func main() {
	app := fiber.New()
	r := fiberopenapi.NewRouter(app,
		fiberopenapi.WithTitle("My API"),
		fiberopenapi.WithVersion("1.0.0"),
		fiberopenapi.WithDescription("This is a sample API"),
		fiberopenapi.WithDocsPath("/docs"),
		fiberopenapi.WithServer("http://localhost:3000", "Local server"),
		fiberopenapi.WithSecurity("bearerAuth", fiberopenapi.SecurityHTTPBearer()),
	)

	api := r.Group("/api")
	v1 := api.Group("/v1")

	v1.Route("/auth", func(r fiberopenapi.Router) {
		r.Post("/login", dummyHandler).With(
			option.Summary("User Login"),
			option.Description("Endpoint for user login"),
			option.Request(new(LoginRequest)),
			option.Response(200, new(Response[Token])),
			option.Response(400, new(ErrorResponse)),
			option.Response(422, new(ValidationResponse)),
		)
		r.Get("/me", dummyHandler).With(
			option.Summary("Get User Profile"),
			option.Description("Endpoint to get the authenticated user's profile"),
			option.Security("bearerAuth"),
			option.Response(200, new(Response[UserProfile])),
			option.Response(401, new(ErrorResponse)),
		)
	}, option.WithRouteTags("Authentication"))

	v1.Route("/profile", func(r fiberopenapi.Router) {
		r.Put("/update", dummyHandler).With(
			option.Summary("Update User Profile"),
			option.Description("Endpoint to update the user's profile"),
			option.Request(new(UpdateProfileRequest)),
			option.Response(200, new(Response[UserProfile])),
			option.Response(400, new(ErrorResponse)),
			option.Response(422, new(ValidationResponse)),
		)
	}, option.WithRouteTags("Profile"), option.WithRouteSecurity("bearerAuth"))

	// Validate the OpenAPI configuration
	if err := r.Validate(); err != nil {
		panic(err)
	}

	app.Listen(":3000")
}

// Dummy handlers for demonstration purposes
func dummyHandler(c *fiber.Ctx) error {
	return c.SendString("Hello, World!")
}

type LoginRequest struct {
	Username   string `json:"username" example:"john_doe" validate:"required"`
	Password   string `json:"password" example:"password123" validate:"required"`
	RememberMe bool   `json:"remember_me" example:"true"`
}

type UpdateProfileRequest struct {
	Name     string `json:"name" example:"John Doe" validate:"required"`
	Email    string `json:"email" example:"john_doe@example.com" validate:"required,email"`
	Username string `json:"username" example:"john_doe" validate:"required"`
}

type Token struct {
	AccessToken  string `json:"access_token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."`
	RefreshToken string `json:"refresh_token" example:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."`
}

type User struct {
	ID       string `json:"id" example:"12345"`
	Username string `json:"username" example:"john_doe"`
	Email    string `json:"email" example:"john_doe@example.com"`
	Name     string `json:"name" example:"John Doe"`
}

type Response[T any] struct {
	Status int `json:"status" example:"200"`
	Data   T   `json:"data,omitempty"`
}

type ErrorResponse struct {
	Status  int    `json:"status" example:"400"`
	Title   string `json:"title"`
	Detail  string `json:"detail"`
}

type ValidationResponse struct {
	Status int          `json:"status" example:"422"`
	Title  string       `json:"title" example:"Validation Error"`
	Detail string       `json:"detail" example:"Input data does not meet validation criteria"`
	Errors []FieldError `json:"errors" example:"[{\"field\":\"email\",\"message\":\"Email is required\"}]"`
}

type FieldError struct {
	Field   string `json:"field" example:"email"`
	Message string `json:"message" example:"Email is required"`
}

By default, your OpenAPI JSON and Swagger UI will be served at /docs.

More Examples

See the examples directory for more practical use cases.

Configuration Options

Global OpenAPI Options
  • Title: API title.
  • Version: API version.
  • Description: API description.
  • BaseURL: Base URL for your API (e.g., https://api.example.com).
  • DocsPath: Path to serve OpenAPI docs and Swagger UI.
  • Server: Define server URL and description.
  • Security: Register security schemes like API keys or Bearer tokens.
  • Swagger: Configure Swagger UI options.
Route Options (With)
  • Summary: Short summary of the route.
  • Description: Detailed description.
  • Request: Request body schema.
  • Response: Response schemas for status codes.
  • Tags: Tags for grouping routes.
  • Security: Route-specific security requirements.
  • Deprecated: Mark route as deprecated.
  • Hide: Exclude route from OpenAPI documentation.

Struct Tags

This package uses openapi-go for schema generation. Supported tags include:

  • json: JSON field name.
  • query: Query parameter name.
  • path: Path parameter name.
  • header: Header parameter name.
  • formData: Form data parameter name.
  • title: Custom title for the field.
  • description: Description for the field.

For more details, see the openapi-go and jsonschema-go documentation.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

Package fiberopenapi provides an OpenAPI documentation generator for Fiber applications.

This package wraps the Fiber router and provides methods to define OpenAPI specifications, security schemes, and serve the Swagger UI.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ConfigOption

type ConfigOption func(*config)

ConfigOption defines a function that applies configuration to the OpenAPI router.

func WithBaseURL

func WithBaseURL(baseURL string) ConfigOption

WithBaseURL sets the base URL for the OpenAPI documentation.

func WithDescription

func WithDescription(description string) ConfigOption

WithDescription sets the description for the OpenAPI documentation.

func WithDocsPath

func WithDocsPath(path string) ConfigOption

WithDocsPath sets the path for the OpenAPI documentation.

func WithOpenAPI

func WithOpenAPI(enable ...bool) ConfigOption

WithOpenAPI enables or disables the OpenAPI functionality.

If true, OpenAPI functionality is enabled; if false, it is disabled. By default, OpenAPI is enabled.

It can be used to conditionally disable OpenAPI at production environment.

func WithSecurity

func WithSecurity(name string, opts ...SecurityOption) ConfigOption

WithSecurity adds a security scheme to the OpenAPI documentation.

It can be used to define API key or HTTP Bearer authentication schemes.

func WithServer

func WithServer(url string, description ...string) ConfigOption

WithServer adds a server to the OpenAPI documentation.

func WithSwaggerConfig

func WithSwaggerConfig(cfg ...*SwaggerConfig) ConfigOption

WithSwagger sets the configuration for Swagger UI.

func WithTitle

func WithTitle(title string) ConfigOption

WithTitle sets the title for the OpenAPI documentation.

func WithVersion

func WithVersion(version string) ConfigOption

WithVersion sets the version for the 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.RouteOption) Router

	// Validate checks for errors at OpenAPI router initialization.
	//
	// It returns an error if there are issues with the OpenAPI configuration.
	Validate() error

	// GenerateOpenAPISchema generates the OpenAPI schema in the specified format.
	// Supported formats are "json" and "yaml".
	// If no format is specified, "yaml" is used by default.
	GenerateOpenAPISchema(format ...string) ([]byte, error)

	WriteSchemaTo(filePath string) error
}

Router defines the interface for an OpenAPI router.

func NewRouter

func NewRouter(r fiber.Router, opts ...ConfigOption) Router

NewRouter creates a new OpenAPI router with the specified Fiber router and options. It initializes the OpenAPI reflector and sets up the documentation routes. If OpenAPI is disabled, it returns a router without OpenAPI functionality.

type SecurityOption

type SecurityOption func(*securityConfig)

SecurityOption is a function that applies configuration to a securityConfig.

func SecurityAPIKey

func SecurityAPIKey(name string, in openapi31.SecuritySchemeAPIKeyIn) SecurityOption

SecurityAPIKey creates a security scheme for API key authentication.

func SecurityDescription

func SecurityDescription(description string) SecurityOption

SecurityDescription sets the description for the security scheme.

func SecurityHTTPBearer

func SecurityHTTPBearer(scheme ...string) SecurityOption

SecurityHTTPBearer creates a security scheme for HTTP Bearer authentication.

func SecurityOauth2

func SecurityOauth2(flows openapi31.OauthFlows) SecurityOption

SecurityOauth2 creates a security scheme for OAuth 2.0 authentication.

type SwaggerConfig

type SwaggerConfig struct {
	ShowTopBar         bool
	HideCurl           bool
	JsonEditor         bool
	PreAuthorizeApiKey map[string]string

	// SettingsUI contains keys and plain javascript values of SwaggerUIBundle configuration.
	// Overrides default values.
	// See https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ for available options.
	SettingsUI map[string]string

	// Proxy enables proxying requests through swgui handler.
	// Can be useful if API is not directly available due to CORS policy.
	Proxy bool
}

SwaggerConfig holds the configuration for Swagger UI.

Directories

Path Synopsis
cmd
generate-schema command
examples
basic module
internal
dto
tools command

Jump to

Keyboard shortcuts

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