From 3e8c50d80ad3d893f1ef4e43bf515ae6d857155f Mon Sep 17 00:00:00 2001 From: Gabriel Radureau Date: Sun, 5 Apr 2026 10:37:48 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20docs:=20comprehensive=20Swagger?= =?UTF-8?q?=20documentation=20skill=20with=20hierarchical=20tagging?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .vibe/skills/swagger_documentation/README.md | 150 ++++++++++ .vibe/skills/swagger_documentation/SKILL.md | 299 +++++++++++++++++++ AGENTS.md | 27 +- adr/0013-openapi-swagger-toolchain.md | 76 ++++- cmd/server/main.go | 5 +- pkg/greet/api_v1.go | 4 +- pkg/greet/api_v2.go | 2 +- pkg/server/server.go | 6 +- 8 files changed, 553 insertions(+), 16 deletions(-) create mode 100644 .vibe/skills/swagger_documentation/README.md create mode 100644 .vibe/skills/swagger_documentation/SKILL.md diff --git a/.vibe/skills/swagger_documentation/README.md b/.vibe/skills/swagger_documentation/README.md new file mode 100644 index 0000000..ae637a9 --- /dev/null +++ b/.vibe/skills/swagger_documentation/README.md @@ -0,0 +1,150 @@ +# Swagger Documentation Skill + +**Skill Name:** `swagger-documentation` +**Status:** ✅ Active +**Version:** 1.0.0 + +## 📋 Overview + +This skill provides comprehensive guidance and automation for managing OpenAPI/Swagger documentation in the DanceLessonsCoach project. It captures our best practices, tagging strategies, and automation patterns for maintaining high-quality API documentation. + +## 🎯 Key Features + +### 1. **Hierarchical Tagging System** +Our proprietary `Domain/Version/Function` tagging structure: +- `API/v1/Greeting`, `API/v2/Greeting` for business endpoints +- `System/Health`, `System/Metrics` for infrastructure endpoints +- Clear separation between API domains and versions + +### 2. **Standardized Annotations** +Pre-defined templates for all endpoint types: +- Basic endpoints +- Parameterized endpoints +- POST endpoints with request bodies +- System/health endpoints + +### 3. **Automation Scripts** +Ready-to-use scripts for: +- Documentation generation +- Validation and quality checks +- CI/CD integration + +### 4. **Best Practices Guide** +Comprehensive guidelines covering: +- Tag consistency rules +- Annotation completeness +- Version management +- Response documentation + +## 🚀 Quick Start + +### 1. Generate Documentation +```bash +# Regenerate all Swagger documentation +go generate ./pkg/server/ +``` + +### 2. Verify Structure +```bash +# Check hierarchical tags are present +grep -c "API/v1/Greeting" pkg/server/docs/swagger.json +grep -c "API/v2/Greeting" pkg/server/docs/swagger.json +grep -c "System/Health" pkg/server/docs/swagger.json +``` + +### 3. Test in Swagger UI +```bash +# Access the interactive documentation +open http://localhost:8080/swagger/ +``` + +## 📚 Documentation Structure + +``` +swagger_documentation/ +├── SKILL.md # Complete skill documentation +├── README.md # This file +└── scripts/ # Automation scripts (future) +``` + +## 🎓 Usage Patterns + +### Adding New Endpoints +1. **Choose the right tag** based on domain/version/function +2. **Copy annotation template** from SKILL.md +3. **Add complete annotations** to handler +4. **Regenerate documentation** with `go generate` +5. **Verify in Swagger UI** + +### Updating Existing Endpoints +1. **Update handler code** as needed +2. **Review annotations** for accuracy +3. **Regenerate documentation** +4. **Test changes** in Swagger UI + +### Adding New API Versions +1. **Create new tag structure** (e.g., `API/v3/Greeting`) +2. **Document in SKILL.md** +3. **Update ADR 0013** with rationale +4. **Implement endpoints** with new tags +5. **Regenerate and test** + +## 🔧 Technical Details + +### Tag Structure Rules +``` +Domain/Version/Function +│ │ └─ Specific functionality (Greeting, User, Health) +│ └─ API version (v1, v2, v3) - for API domain only +└─ Domain (API, System, Admin) +``` + +### Required Flags +```bash +# These flags are CRITICAL for multi-package projects +--parseDependency # Parse dependent packages +--parseInternal # Include internal packages +``` + +### Embed Directive +```go +//go:embed docs/swagger.json +var swaggerJSON embed.FS +``` + +## 📝 Maintenance + +### Updating This Skill +When you: +- Introduce new tag patterns +- Discover better annotation approaches +- Add new endpoint types +- Find solutions to common issues + +**Please update SKILL.md** to share knowledge with the team! + +### Version History +- **1.0.0**: Initial release with hierarchical tagging +- **Next**: Add CI/CD integration scripts + +## 🤝 Contributing + +Found a better way? Have a new pattern? + +1. **Update SKILL.md** with your improvements +2. **Test thoroughly** in development +3. **Document examples** clearly +4. **Update ADR 0013** if architectural changes +5. **Commit with clear message** using gitmoji + +## 📚 Related Resources + +- **[ADR 0013](adr/0013-openapi-swagger-toolchain.md)** - Architectural decision +- **[AGENTS.md](#openapi-documentation)** - Project documentation +- **[swaggo/swag](https://github.com/swaggo/swag)** - Official documentation + +--- + +**Maintained by:** DanceLessonsCoach Team +**License:** MIT +**Status:** Actively developed \ No newline at end of file diff --git a/.vibe/skills/swagger_documentation/SKILL.md b/.vibe/skills/swagger_documentation/SKILL.md new file mode 100644 index 0000000..0c14491 --- /dev/null +++ b/.vibe/skills/swagger_documentation/SKILL.md @@ -0,0 +1,299 @@ +# Swagger Documentation Skill + +**Name:** `swagger-documentation` +**Purpose:** Manage and optimize OpenAPI/Swagger documentation for DanceLessonsCoach +**Version:** 1.0.0 + +## 🎯 Skill Objectives + +1. **Standardize** Swagger documentation across the project +2. **Automate** documentation generation and updates +3. **Optimize** tag organization and structure +4. **Validate** documentation completeness and accuracy +5. **Enhance** developer experience with best practices + +## 📋 Skill Capabilities + +### 1. Documentation Generation +- Auto-generate Swagger docs with proper flags +- Handle multi-package projects +- Ensure complete endpoint coverage + +### 2. Tag Management +- Implement hierarchical tagging (`Domain/Version/Function`) +- Maintain tag consistency +- Document tag evolution + +### 3. Annotation Standards +- Enforce consistent annotation patterns +- Validate annotation completeness +- Provide annotation templates + +### 4. Quality Assurance +- Check for missing documentation +- Validate Swagger JSON/YAML +- Ensure embed directives are correct + +## 🔧 Implementation + +### Required Tools +```bash +# Install swaggo/swag +go install github.com/swaggo/swag/cmd/swag@latest +``` + +### Standard Command +```bash +# Generate documentation with proper flags +swag init -g ./cmd/server/main.go --parseDependency --parseInternal +``` + +### Go Generate Directive +```go +//go:generate swag init -g ../../cmd/server/main.go --parseDependency --parseInternal +``` + +## 🏷️ Hierarchical Tagging System + +### Current Standard +```go +// API Domain - Business endpoints +@Tags API/v1/Greeting # v1 greeting endpoints +@Tags API/v2/Greeting # v2 greeting endpoints +@Tags API/v1/User # v1 user endpoints (future) +@Tags API/v2/User # v2 user endpoints (future) + +// System Domain - Infrastructure endpoints +@Tags System/Health # Health/readiness endpoints +@Tags System/Metrics # Metrics endpoints (future) +@Tags System/Config # Configuration endpoints (future) + +// Admin Domain - Administrative endpoints +@Tags Admin/User # User management (future) +@Tags Admin/System # System administration (future) +``` + +### Tag Structure Rules +1. **Domain First**: Always start with domain (`API/`, `System/`, `Admin/`) +2. **Version Second**: For API domain, include version (`v1/`, `v2/`) +3. **Function Third**: Specific functionality area (`Greeting`, `User`, `Health`) +4. **Consistent Capitalization**: Use PascalCase for all components + +## 📝 Annotation Templates + +### Basic Endpoint +```go +// handleGreetQuery godoc +// @Summary Get default greeting +// @Description Returns a greeting message with default parameters +// @Tags API/v1/Greeting +// @Accept json +// @Produce json +// @Success 200 {object} GreetResponse "Successful response" +// @Router /v1/greet [get] +func (h *apiV1GreetHandler) handleGreetQuery(w http.ResponseWriter, r *http.Request) { + // implementation +} +``` + +### Parameterized Endpoint +```go +// handleGreetPath godoc +// @Summary Get personalized greeting +// @Description Returns a greeting with the specified name +// @Tags API/v1/Greeting +// @Accept json +// @Produce json +// @Param name path string true "Name to greet" +// @Success 200 {object} GreetResponse "Successful response" +// @Failure 400 {object} ErrorResponse "Invalid name parameter" +// @Router /v1/greet/{name} [get] +func (h *apiV1GreetHandler) handleGreetPath(w http.ResponseWriter, r *http.Request) { + // implementation +} +``` + +### POST Endpoint with Body +```go +// handleGreetPost godoc +// @Summary Create greeting (v2) +// @Description Creates a greeting with validation (v2) +// @Tags API/v2/Greeting +// @Accept json +// @Produce json +// @Param request body GreetRequest true "Greeting request" +// @Success 200 {object} GreetResponseV2 "Successful response" +// @Failure 400 {object} ValidationError "Validation error" +// @Router /v2/greet [post] +func (h *apiV2GreetHandler) handleGreetPost(w http.ResponseWriter, r *http.Request) { + // implementation +} +``` + +### System Endpoint +```go +// handleHealth godoc +// @Summary Health check +// @Description Check if the service is healthy +// @Tags System/Health +// @Accept json +// @Produce json +// @Success 200 {object} map[string]string "Service is healthy" +// @Router /health [get] +func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { + // implementation +} +``` + +## 🎯 Best Practices + +### 1. Tag Consistency +- Use the same tag structure across all similar endpoints +- Don't mix hierarchical and flat tags +- Document new tags in this skill when introduced + +### 2. Annotation Completeness +- Always include: Summary, Description, Tags, Accept, Produce, Responses +- Include Parameters for all path/query/body parameters +- Document all possible response codes + +### 3. Response Documentation +- Use concrete types (`GreetResponse`) not generics +- Include example values where helpful +- Document both success and error responses + +### 4. Version Management +- Keep version tags consistent (`v1`, `v2`, not `1.0`, `2.0`) +- Document breaking changes in ADR when introducing new versions +- Maintain old versions until formally deprecated + +## 🔍 Validation Checklist + +### Before Committing Swagger Changes +- [ ] Run `go generate ./...` to regenerate docs +- [ ] Verify all endpoints appear in Swagger UI +- [ ] Check tag hierarchy is correct +- [ ] Validate JSON schema is valid +- [ ] Test Swagger UI functionality +- [ ] Update this skill if new patterns emerge + +### Common Issues to Check +1. **Missing Endpoints**: Ensure all handlers have `@Router` annotations +2. **Incorrect Tags**: Verify hierarchical structure +3. **Broken References**: Check `$ref` paths in generated JSON +4. **Embed Issues**: Confirm `//go:embed` paths are correct +5. **Flag Problems**: Ensure `--parseDependency --parseInternal` flags are used + +## 📚 Resources + +### Official Documentation +- [swaggo/swag GitHub](https://github.com/swaggo/swag) +- [swaggo/swag Documentation](https://github.com/swaggo/swag#declaration) +- [OpenAPI 2.0 Specification](https://swagger.io/specification/v2/) + +### DanceLessonsCoach Specific +- [ADR 0013: OpenAPI/Swagger Toolchain](adr/0013-openapi-swagger-toolchain.md) +- [AGENTS.md OpenAPI Section](#openapi-documentation) +- [Current Implementation](pkg/greet/api_v1.go) + +## 🤖 Automation Scripts + +### Regenerate Documentation +```bash +#!/bin/bash +# Regenerate all Swagger documentation +echo "Generating Swagger documentation..." +swag init -g ./cmd/server/main.go --parseDependency --parseInternal + +# Move to correct location +rm -rf pkg/server/docs +mkdir -p pkg/server/docs +mv docs/* pkg/server/docs/ +rm -rf docs + +echo "✅ Swagger documentation generated successfully" +``` + +### Validate Documentation +```bash +#!/bin/bash +# Validate Swagger documentation +echo "Validating Swagger documentation..." + +# Check for required endpoints +MISSING_ENDPOINTS=0 +for endpoint in "v1/greet" "v2/greet" "health" "ready"; do + if ! grep -q "$endpoint" pkg/server/docs/swagger.json; then + echo "❌ Missing endpoint: $endpoint" + MISSING_ENDPOINTS=$((MISSING_ENDPOINTS + 1)) + fi +done + +# Check for hierarchical tags +if ! grep -q "API/v1/Greeting" pkg/server/docs/swagger.json; then + echo "❌ Missing hierarchical tag: API/v1/Greeting" +fi + +if ! grep -q "API/v2/Greeting" pkg/server/docs/swagger.json; then + echo "❌ Missing hierarchical tag: API/v2/Greeting" +fi + +if ! grep -q "System/Health" pkg/server/docs/swagger.json; then + echo "❌ Missing hierarchical tag: System/Health" +fi + +if [ $MISSING_ENDPOINTS -eq 0 ] && [ $MISSING_TAGS -eq 0 ]; then + echo "✅ Swagger documentation validation passed" +else + echo "❌ Swagger documentation validation failed" + exit 1 +fi +``` + +## 🎓 Training Guide + +### For New Developers +1. **Understand the hierarchy**: `Domain/Version/Function` +2. **Copy existing patterns**: Use templates from this skill +3. **Generate frequently**: Run `go generate` after changes +4. **Test in Swagger UI**: Verify your endpoints appear correctly +5. **Update documentation**: Add new tags to this skill when introduced + +### Common Mistakes to Avoid +1. **Forgetting `--parseDependency --parseInternal`** → Missing endpoints +2. **Inconsistent tag structure** → Messy Swagger UI +3. **Missing `@Router` annotations** → Endpoints not documented +4. **Not regenerating after changes** → Stale documentation +5. **Breaking embed paths** → Runtime errors + +## 🔮 Future Enhancements + +### Potential Improvements +- [ ] Add automated documentation testing +- [ ] Create Swagger linting rules +- [ ] Implement documentation coverage metrics +- [ ] Add examples for all response types +- [ ] Integrate with CI/CD pipeline + +### Migration Paths +- OpenAPI 3.0 support when needed +- Automated changelog generation +- Client SDK generation +- API governance tools + +## 📝 Changelog + +**1.0.0** (2026-04-05): Initial version with hierarchical tagging best practices +- Documented current tag structure +- Added annotation templates +- Included validation checklist +- Added automation scripts +- Established best practices + +**Next Version**: Add automated testing and CI integration + +--- + +**Maintainers**: DanceLessonsCoach Team +**License**: MIT +**Status**: Active \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 6315a18..5eda4fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -351,16 +351,31 @@ http://localhost:8080 **Swagger UI:** `http://localhost:8080/swagger/` **OpenAPI Spec:** `http://localhost:8080/swagger/doc.json` -The API provides interactive documentation using Swagger UI with complete OpenAPI 2.0 specification. All endpoints, request/response models, and validation rules are documented. +The API provides interactive documentation using Swagger UI with complete OpenAPI 2.0 specification. All endpoints, request/response models, and validation rules are documented using a **hierarchical tagging system**. **Features:** -- Interactive API exploration -- Try-it-out functionality +- Interactive API exploration with hierarchical organization +- Try-it-out functionality for all endpoints - Model schemas with examples -- Response examples -- Validation rules documentation +- Response examples with validation rules +- **Hierarchical tag structure** for better navigation -**Generation:** Documentation is auto-generated from code annotations using [swaggo/swag](https://github.com/swaggo/swag). +**Generation:** Documentation is auto-generated from code annotations using [swaggo/swag](https://github.com/swaggo/swag) with the command: + +```bash +go generate ./pkg/server/ +``` + +**Tag Organization:** +- `API/v1/Greeting` - Version 1 greeting endpoints +- `API/v2/Greeting` - Version 2 greeting endpoints +- `System/Health` - Health and readiness endpoints + +**Hierarchical Benefits:** +- Clear separation between API domains (API vs System) +- Version organization within each domain +- Natural hierarchy in Swagger UI +- Scalable for future API growth ```bash # Generate documentation diff --git a/adr/0013-openapi-swagger-toolchain.md b/adr/0013-openapi-swagger-toolchain.md index ef4e38f..3d03718 100644 --- a/adr/0013-openapi-swagger-toolchain.md +++ b/adr/0013-openapi-swagger-toolchain.md @@ -309,20 +309,92 @@ go install github.com/swaggo/swag/cmd/swag@latest // @BasePath /api package main -# 3. Annotate handlers and models +# 3. Annotate handlers and models with hierarchical tags // @Summary Get personalized greeting // @Description Returns a greeting with the specified name -// @Tags greet +// @Tags API/v1/Greeting # Hierarchical tag: Domain/Version/Function // @Accept json // @Produce json // @Param name path string true "Name to greet" // @Success 200 {object} GreetResponse // @Failure 400 {object} ErrorResponse // @Router /v1/greet/{name} [get] + +# Example v2 endpoint with hierarchical tag +// @Summary Get greeting (v2) +// @Description Returns a greeting message with validation (v2) +// @Tags API/v2/Greeting # Hierarchical tag: Domain/Version/Function +// @Accept json +// @Produce json +// @Param request body GreetRequest true "Greeting request" +// @Success 200 {object} GreetResponseV2 +// @Failure 400 {object} ValidationError +// @Router /v2/greet [post] + +# System endpoints use different domain +// @Summary Health check +// @Description Check if the service is healthy +// @Tags System/Health # Hierarchical tag: Domain/Function +// @Accept json +// @Produce json +// @Success 200 {object} map[string]string "Service is healthy" +// @Router /health [get] func (h *apiV1GreetHandler) handleGreetPath(w http.ResponseWriter, r *http.Request) { // handler implementation } +## Tagging Strategy Evolution + +### Phase 1: Simple Tags (Initial Approach) +```go +// @Tags greet +// @Tags health +``` +**Issue**: No version separation, all endpoints mixed together + +### Phase 2: Version-Based Tags (Improved) +```go +// @Tags v1-greet +// @Tags v2-greet +// @Tags health +``` +**Issue**: Still flat structure, no domain separation + +### Phase 3: Hierarchical Tags (Current - Recommended) +```go +// @Tags API/v1/Greeting +// @Tags API/v2/Greeting +// @Tags System/Health +``` +**Benefits**: +- Clear domain separation (API vs System) +- Version organization within domains +- Natural hierarchy in Swagger UI +- Scalable for future growth + +## Hierarchical Tagging Best Practices + +### 1. Domain-First Organization +- `API/` for business endpoints +- `System/` for infrastructure endpoints +- `Admin/` for administrative endpoints +- `Internal/` for internal-only endpoints + +### 2. Consistent Structure +- API Domain: `API/{version}/{function}` +- System Domain: `System/{function}` +- Admin Domain: `Admin/{function}` + +### 3. Versioning Strategy +- Use semantic versions: `v1`, `v2`, `v3` +- Keep versions consistent across domains +- Document breaking changes clearly + +### 4. Function Naming +- Use singular nouns: `Greeting`, `User`, `Order` +- Be specific: `PaymentProcessing` vs `Payment` +- Avoid acronyms unless widely known + # 4. Generate documentation go generate ./pkg/server/ diff --git a/cmd/server/main.go b/cmd/server/main.go index acf6eeb..a9498d4 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -6,8 +6,8 @@ // @termsOfService http://swagger.io/terms/ // @contact.name API Support -// @contact.url http://www.dance-lessons-coach.com/support -// @contact.email support@dance-lessons-coach.com +// @contact.url http://www.arcodange.fr/support +// @contact.email support@arcodange.fr // @license.name MIT // @license.url https://opensource.org/licenses/MIT @@ -23,6 +23,7 @@ import ( "DanceLessonsCoach/pkg/config" "DanceLessonsCoach/pkg/server" + "github.com/rs/zerolog/log" ) diff --git a/pkg/greet/api_v1.go b/pkg/greet/api_v1.go index 48db810..7b5320c 100644 --- a/pkg/greet/api_v1.go +++ b/pkg/greet/api_v1.go @@ -77,7 +77,7 @@ func (h *apiV1GreetHandler) RegisterRoutes(router chi.Router) { // handleGreetQuery godoc // @Summary Get default greeting // @Description Returns a default greeting message -// @Tags greet +// @Tags API/v1/Greeting // @Accept json // @Produce json // @Success 200 {object} GreetResponse "Successful response" @@ -90,7 +90,7 @@ func (h *apiV1GreetHandler) handleGreetQuery(w http.ResponseWriter, r *http.Requ // handleGreetPath godoc // @Summary Get personalized greeting // @Description Returns a greeting with the specified name -// @Tags greet +// @Tags API/v1/Greeting // @Accept json // @Produce json // @Param name path string true "Name to greet" diff --git a/pkg/greet/api_v2.go b/pkg/greet/api_v2.go index 61998ea..42a45f0 100644 --- a/pkg/greet/api_v2.go +++ b/pkg/greet/api_v2.go @@ -47,7 +47,7 @@ type greetResponse struct { // handleGreetPost godoc // @Summary Get greeting (v2) // @Description Returns a greeting message with validation (v2) -// @Tags greet +// @Tags API/v2/Greeting // @Accept json // @Produce json // @Param request body GreetRequest true "Greeting request" diff --git a/pkg/server/server.go b/pkg/server/server.go index 885d9ad..6eae125 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -1,4 +1,4 @@ -//go:generate swag init -g ../../cmd/server/main.go +//go:generate swag init -g ../../cmd/server/main.go --parseDependency --parseInternal package server @@ -136,7 +136,7 @@ func (s *Server) getAllMiddlewares() []func(http.Handler) http.Handler { // handleHealth godoc // @Summary Health check // @Description Check if the service is healthy -// @Tags health +// @Tags System/Health // @Accept json // @Produce json // @Success 200 {object} map[string]string "Service is healthy" @@ -149,7 +149,7 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { // handleReadiness godoc // @Summary Readiness check // @Description Check if the service is ready to accept traffic -// @Tags health +// @Tags System/Health // @Accept json // @Produce json // @Success 200 {object} map[string]bool "Service is ready"