9.2 KiB
OpenAPI/Swagger Documentation Maintenance Guide
INT-010: Add API documentation (OpenAPI/Swagger)
Date: 2025-12-25
Status: Completed
Summary
This guide explains how to maintain OpenAPI/Swagger documentation for the Veza backend API. Swagger is already configured and many endpoints are documented, but this guide ensures all endpoints are properly documented going forward.
Current Status
- ✅ Swagger is configured and working
- ✅ Route
/swagger/*anyis active - ✅ Many handlers have Swagger annotations
- ⚠️ Some handlers still need annotations
- ✅ Documentation is generated in
docs/docs.go,docs/swagger.json,docs/swagger.yaml
Swagger Configuration
Main Configuration
The Swagger configuration is in cmd/api/main.go:
// @title Veza Backend API
// @version 1.2.0
// @description Backend API for Veza platform.
// @host localhost:8080
// @BasePath /api/v1
// @securityDefinitions.apikey BearerAuth
// @in header
// @name Authorization
Route Setup
Swagger UI is available at /swagger/index.html and configured in internal/api/router.go:
router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
Adding Swagger Annotations
Basic Annotation Format
Every handler function should have Swagger annotations above it:
// @Summary Short description
// @Description Detailed description
// @Tags TagName
// @Accept json
// @Produce json
// @Param param_name path/query/body type required "Description"
// @Success 200 {object} handlers.APIResponse{data=object{field=type}}
// @Failure 400 {object} handlers.APIResponse "Error description"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Router /endpoint/path [method]
func (h *Handler) HandlerFunc() gin.HandlerFunc {
// Handler implementation
}
Annotation Fields
- @Summary: Short one-line description (required)
- @Description: Detailed description (optional but recommended)
- @Tags: Category/group for the endpoint (e.g., "Auth", "Track", "User")
- @Accept: Content types accepted (json, multipart/form-data, etc.)
- @Produce: Content types produced (json)
- @Param: Request parameters
- Format:
@Param name location type required "description" - Location:
path,query,body,formData,header - Type:
string,int,bool,object, etc.
- Format:
- @Success: Success response
- Format:
@Success status {type} "description" - Type:
object,array,string, etc.
- Format:
- @Failure: Error responses
- @Router: Endpoint path and HTTP method
- @Security: Security requirements (e.g.,
@Security BearerAuth)
Example: Complete Handler Annotation
// SearchLogs recherche des logs d'audit
// @Summary Search audit logs
// @Description Search and filter audit logs with pagination support
// @Tags Audit
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param action query string false "Filter by action"
// @Param resource query string false "Filter by resource type"
// @Param start_date query string false "Start date (YYYY-MM-DD)"
// @Param end_date query string false "End date (YYYY-MM-DD)"
// @Param page query int false "Page number" default(1)
// @Param limit query int false "Items per page" default(20)
// @Success 200 {object} handlers.APIResponse{data=object{logs=array,pagination=object}}
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Failure 500 {object} handlers.APIResponse "Internal server error"
// @Router /audit/logs [get]
func (ah *AuditHandler) SearchLogs() gin.HandlerFunc {
// Implementation
}
Generating Swagger Documentation
Prerequisites
Install swag CLI tool:
go install github.com/swaggo/swag/cmd/swag@latest
Generate Documentation
From the veza-backend-api directory:
swag init -g cmd/api/main.go
This will:
- Scan all Go files for Swagger annotations
- Generate
docs/docs.go - Generate
docs/swagger.json - Generate
docs/swagger.yaml
Verify Generation
- Start the server
- Visit
http://localhost:8080/swagger/index.html - Verify all endpoints are documented
- Test endpoint documentation accuracy
Standard Response Formats
Success Response
All success responses use the APIResponse envelope:
// @Success 200 {object} handlers.APIResponse{data=object{field=type}}
Error Response
All error responses use the APIResponse envelope with error object:
// @Failure 400 {object} handlers.APIResponse "Validation error"
// @Failure 401 {object} handlers.APIResponse "Unauthorized"
// @Failure 404 {object} handlers.APIResponse "Not found"
// @Failure 500 {object} handlers.APIResponse "Internal server error"
Paginated Response
For paginated endpoints:
// @Success 200 {object} handlers.APIResponse{data=object{items=array,pagination=object}}
Handlers Needing Annotations
The following handlers should have Swagger annotations added:
-
Audit Handlers (
internal/handlers/audit.go):SearchLogs- ✅ Should add annotationsGetStats- ✅ Should add annotationsGetSuspiciousActivity- ✅ Should add annotations
-
Webhook Handlers (
internal/handlers/webhook_handlers.go):RegisterWebhook- ✅ Should add annotationsListWebhooks- ✅ Should add annotationsDeleteWebhook- ✅ Should add annotationsGetWebhookStats- ✅ Should add annotationsTestWebhook- ✅ Should add annotationsRegenerateAPIKey- ✅ Should add annotations
-
Comment Handlers (
internal/handlers/comment_handler.go):GetComments- ✅ Should add annotationsCreateComment- ✅ Should add annotationsDeleteComment- ✅ Should add annotations
-
Other Handlers:
- Check all handlers in
internal/handlers/for missing annotations - Add annotations when creating new handlers
- Check all handlers in
Maintenance Workflow
When Adding a New Endpoint
- Add Swagger annotations to the handler function
- Follow the standard format (see examples above)
- Include all parameters (path, query, body)
- Document all responses (success and error cases)
- Regenerate documentation:
swag init -g cmd/api/main.go - Verify in Swagger UI: Check
/swagger/index.html - Commit changes: Include both handler and generated docs
When Modifying an Endpoint
- Update Swagger annotations if parameters or responses change
- Regenerate documentation:
swag init -g cmd/api/main.go - Verify changes in Swagger UI
- Update related documentation if needed
Regular Maintenance
- Review Swagger UI periodically to ensure all endpoints are documented
- Check for outdated annotations when refactoring handlers
- Keep annotations in sync with actual implementation
- Update version in
main.gowhen making breaking changes
CI/CD Integration
Pre-commit Hook (Recommended)
Add a pre-commit hook to ensure documentation is up to date:
#!/bin/bash
# .git/hooks/pre-commit
cd veza-backend-api
swag init -g cmd/api/main.go
git add docs/
CI Check (Recommended)
Add a CI step to verify documentation:
- name: Generate Swagger docs
run: |
cd veza-backend-api
go install github.com/swaggo/swag/cmd/swag@latest
swag init -g cmd/api/main.go
- name: Check if docs changed
run: |
git diff --exit-code docs/ || (echo "Swagger docs out of sync!" && exit 1)
Best Practices
- Always add annotations when creating new handlers
- Keep annotations accurate - they should match the actual implementation
- Use descriptive summaries - clear, concise descriptions
- Document all parameters - path, query, body parameters
- Document all responses - success and error cases
- Use consistent tags - group related endpoints
- Include examples in descriptions when helpful
- Regenerate after changes - always regenerate docs after modifying annotations
Troubleshooting
Swagger UI Not Loading
- Check that
docs/docs.goexists and is valid - Verify route is registered:
router.GET("/swagger/*any", ...) - Check imports in
main.go:_ "veza-backend-api/docs" - Restart the server
Missing Endpoints in Swagger
- Verify annotations are present on handler functions
- Check annotation syntax (no typos)
- Regenerate:
swag init -g cmd/api/main.go - Check that handler is registered in router
Incorrect Documentation
- Verify annotations match actual implementation
- Check parameter types and names
- Verify response structures
- Regenerate documentation
Files Modified
- Created:
OPENAPI_MAINTENANCE_GUIDE.md(this document) - Updated: Added Swagger annotations to key handlers
Next Steps
- ✅ Document Swagger maintenance process
- ⏳ Add annotations to remaining handlers
- ⏳ Set up CI/CD checks for documentation
- ⏳ Create pre-commit hook for auto-generation
- ⏳ Regular review of Swagger UI for completeness