OpenAPI
OpenAPI Documentation
This project demonstrates how to add OpenAPI 3 documentation to a Go application using Huma.
This project got inspired by the swagger recipe.
Prerequisites
Ensure you have the following installed:
- Golang
- PostgreSQL, reachable with the credentials you put in
.env
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/openapiDownload Go modules:
go mod tidyCopy the example environment file and set your PostgreSQL connection details (
DB_USER,DB_PASSWORD,DB_HOST,DB_NAME,DB_PORT):cp .env.example .env
Running the Application
Start the application:
go run main.goAccess the API Documentation: Open your browser and navigate to
http://localhost:3000/docs.OpenAPI Specs:
- OpenAPI 3.1 JSON:
http://localhost:3000/openapi.json. - OpenAPI 3.1 YAML:
http://localhost:3000/openapi.yaml. - OpenAPI 3.0.3 JSON:
http://localhost:3000/openapi-3.0.json. - OpenAPI 3.0.3 YAML:
http://localhost:3000/openapi-3.0.yaml.
- OpenAPI 3.1 JSON:
Generating TypeScript schema:
npx openapi-typescript http://localhost:3000/openapi.json -o schema.ts
Example
Here is a minimal example of adding huma to a existing Fiber codebase:
routes.go
import (
...
"github.com/gofiber/fiber/v3"
"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humafiber"
)
func New() *fiber.App {
app := fiber.New()
api := humafiber.New(app, huma.DefaultConfig("Book API", "1.0.0"))
// app.Get("/books", handlers.GetAllBooks) // π your existing code
huma.Get(api, "/books", handlers.GetAllBooks) // π huma version
return app
}The recipe itself registers its routes in a /v1 group (huma.NewGroup(api, "/v1")), so its paths are /v1/books and /v1/books/{id}.
handlers/book.go
// func GetAllBooks(c fiber.Ctx) error {} // π your existing code
// π huma version
func GetAllBooks(ctx context.Context, _ *struct{}) (*GetAllBooksResponse, error) {
return &GetAllBooksResponse{Body: books}, nil
}Enhancing Documentation
You can use huma.Register to add more information to the OpenAPI specification, such as descriptions with Markdown, examples, tags, and more.
// huma.Get(group, "/books/{id}", handlers.GetBookByID)
huma.Register(api, huma.Operation{
OperationID: "get-book-by-id",
Method: http.MethodGet,
Path: "/book/{id}",
Summary: "Get a book",
Description: "Get a book by book ID.",
Tags: []string{"Books"},
}, handlers.GetBookByID)