Swagger
Swagger API Documentation
This project demonstrates how to integrate Swagger for API documentation in a Fiber application using gofiber/contrib/swaggerui and swaggo/swag.
Prerequisites
- Go 1.27+
- Swag CLI for generating Swagger docs
- PostgreSQL (connection configured via environment variables)
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/swaggerInstall the Swag CLI:
go install github.com/swaggo/swag/cmd/swag@latestConfigure the database connection via environment variables:
export DB_USER=postgres export DB_PASSWORD=secret export DB_HOST=localhost export DB_NAME=books export DB_PORT=5432
Generating Swagger Docs
Generate (or regenerate) the Swagger documentation from the annotations in your source code:
swag init --parseDependency --parseDependencyLevel 1 --propertyStrategy pascalcaseThis writes docs/docs.go, docs/swagger.json, and docs/swagger.yaml. The first two flags let swag resolve the gorm.Model fields embedded in models.Book. Without them, recent swag versions stop with cannot find type definition: gorm.Model. gorm.Model has no JSON tags, so the API returns its fields as ID, CreatedAt, UpdatedAt and DeletedAt. With the default camelCase naming the documented names would be id, createdAt and so on, and --propertyStrategy pascalcase keeps them in line with the responses.
Running the Application
go run main.goThe application starts on port 3000.
Accessing the Swagger UI
Open your browser and navigate to:
http://localhost:3000/docs/docsThe Swagger UI is served by gofiber/contrib/v3/swaggerui and reads the spec from ./docs/swagger.json.
API Endpoints
All routes are prefixed with /api/v1.
| Method | Path | Description |
|---|---|---|
| GET | /api/v1/books | List all books |
| GET | /api/v1/books/:id | Get a book by ID |
| POST | /api/v1/books | Register a new book |
| DELETE | /api/v1/books/:id | Delete a book by ID |
Example
Annotate your Fiber handler functions with Swag comments to generate docs:
// GetBookByID returns a book by ID
// @Summary Get book by ID
// @Description Get a single book by its ID
// @Tags books
// @Accept json
// @Produce json
// @Param id path int true "Book ID"
// @Success 200 {object} ResponseHTTP{data=models.Book}
// @Failure 404 {object} ResponseHTTP{}
// @Router /v1/books/{id} [get]
func GetBookByID(c fiber.Ctx) error {
// Your code here
}curl Examples
# List all books
curl http://localhost:3000/api/v1/books
# Get book by ID
curl http://localhost:3000/api/v1/books/1
# Create a book
curl -X POST http://localhost:3000/api/v1/books \
-H "Content-Type: application/json" \
-d '{"title":"The Go Programming Language","author":"Donovan & Kernighan"}'
# Delete a book
curl -X DELETE http://localhost:3000/api/v1/books/1