Skip to main content

Swagger/OpenAPI Documentation Integration

This tutorial will guide you through integrating Swagger/OpenAPI documentation into your Gonyx application. You'll learn how to add annotations to your code and generate comprehensive API documentation automatically.

Prerequisites

Before starting this tutorial, make sure you have:

  • A working Gonyx application (see Quick Start if you haven't created one yet)
  • Go 1.19 or later installed
  • Basic knowledge of REST API concepts

What is Swagger/OpenAPI?

Swagger (now known as OpenAPI) is a specification for describing REST APIs. It provides:

  • Interactive Documentation: A web interface where users can explore and test your API endpoints
  • Code Generation: Generate client SDKs in multiple programming languages
  • API Design: Design-first approach to API development
  • Standardization: Industry-standard format for API documentation

Overview

In Gonyx, Swagger integration involves three main steps:

  1. Adding API-level annotations in your app.go file
  2. Adding route-specific annotations in your controller methods
  3. Generating documentation using the gonyx generate swagger command

Step 1: Adding API-Level Annotations

The first step is to add general API information to your application's Init() function in the app.go file. These annotations define metadata about your entire API.

Example: app.go

package app

import (
"gonyx-test-01/app/proto/greeter"

"github.com/Blocktunium/gonyx/pkg/engine"
"github.com/Blocktunium/gonyx/pkg/http"
"google.golang.org/grpc"
)

// App - application engine structure that must satisfy one of the engine interface such as 'engine.RestfulApp', ...
type App struct{}

// Init - initialize the app
//
// @title Gonyx Test API
// @version 1.0
// @description This is a sample API server built with Gonyx framework
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
// @schemes http https
func (app *App) Init() {
engine.RegisterRestfulController(&SampleController{})

greeterService := SampleProtoController{}
engine.RegisterGrpcController(&greeterService, func(server *grpc.Server) {
greeter.RegisterGreeterServer(server, &greeterService)
})

http.PrintAllRoutes()
}

API-Level Annotation Explanations

AnnotationDescriptionExample
@titleThe title of your APIGonyx Test API
@versionAPI version1.0
@descriptionDetailed description of your APIThis is a sample API server built with Gonyx framework
@termsOfServiceURL to terms of servicehttp://swagger.io/terms/
@contact.nameContact name for API supportAPI Support
@contact.urlContact URLhttp://www.swagger.io/support
@contact.emailContact emailsupport@swagger.io
@license.nameLicense nameApache 2.0
@license.urlLicense URLhttp://www.apache.org/licenses/LICENSE-2.0.html
@hostAPI hostlocalhost:8080
@BasePathBase path for all API endpoints/
@schemesSupported schemeshttp https

Step 2: Adding Route-Specific Annotations

Next, you need to add detailed annotations for each API endpoint in your controller methods. These annotations describe the behavior, parameters, and responses of individual routes.

Example: Controller with Swagger Annotations

package app

import (
"context"
"fmt"
"gonyx-test-01/app/proto/greeter"
"os"
"path/filepath"

"github.com/Blocktunium/gonyx/pkg/http"
"github.com/gin-gonic/gin"
)

// UserRequest represents the input JSON structure
type UserRequest struct {
Name string `json:"name" binding:"required"`
Email string `json:"email" binding:"required,email"`
Age int `json:"age" binding:"min=1"`
Message string `json:"message"`
}

// UserResponse represents the output JSON structure
type UserResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
Message string `json:"message"`
ProcessedAt string `json:"processed_at"`
Status string `json:"status"`
}

// SampleController - a sample controller to show the functionality
type SampleController struct{}

// GetName - return the name of the controller to be used as part of the route
func (ctrl *SampleController) GetName() string { return "Sample" }

// Routes - returning controller specific routes to be registered
func (ctrl *SampleController) Routes() []http.HttpRoute {
return []http.HttpRoute{
{
Method: http.MethodGet,
Path: "/hello",
RouteName: "hello",
F: ctrl.GetHello,
},
{
Method: http.MethodPost,
Path: "/user",
RouteName: "create_user",
F: ctrl.CreateUser,
},
}
}

// GetHello godoc
//
// @Summary Get hello message
// @Description Returns a simple "Hello World" greeting message
// @Tags Sample
// @Accept json
// @Produce plain
// @Success 200 {string} string "Hello World"
// @Router /sample/hello [get]
//
// GetHello - just return the 'Hello World' string to user
func (ctrl *SampleController) GetHello(c *gin.Context) {
c.String(200, "Hello World")
}

// CreateUser godoc
//
// @Summary Create a new user
// @Description Creates a new user with the provided information and returns user details
// @Tags Sample
// @Accept json
// @Produce json
// @Param user body UserRequest true "User information"
// @Success 201 {object} UserResponse "User created successfully"
// @Failure 400 {object} map[string]string "Invalid input"
// @Failure 500 {object} map[string]string "Internal server error"
// @Router /sample/user [post]
//
// CreateUser - accepts a JSON object and returns a user struct
func (ctrl *SampleController) CreateUser(c *gin.Context) {
var req UserRequest

// Bind JSON input to struct
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{
"error": "Invalid input: " + err.Error(),
})
return
}

// Process the request and create response
response := UserResponse{
ID: 12345, // In a real app, this would be generated by the database
Name: req.Name,
Email: req.Email,
Age: req.Age,
Message: fmt.Sprintf("Hello %s! Your message '%s' has been received.", req.Name, req.Message),
ProcessedAt: "2025-09-15T15:22:28+03:30", // In a real app, use time.Now()
Status: "created",
}

c.JSON(201, response)
}

Route-Level Annotation Explanations

AnnotationDescriptionExample
@SummaryBrief summary of the endpointGet hello message
@DescriptionDetailed description of what the endpoint doesReturns a simple "Hello World" greeting message
@TagsGroups endpoints in the documentationSample
@AcceptContent types the endpoint acceptsjson
@ProduceContent types the endpoint producesjson, plain
@ParamParameter definitionuser body UserRequest true "User information"
@SuccessSuccess response definition200 {string} string "Hello World"
@FailureError response definition400 {object} map[string]string "Invalid input"
@RouterRoute path and HTTP method/sample/hello [get]

Parameter Types

The @Param annotation supports different parameter types:

  • body: Request body parameter
  • path: URL path parameter (e.g., /user/{id})
  • query: Query string parameter (e.g., ?limit=10)
  • header: HTTP header parameter
  • formData: Form data parameter

Response Types

You can define various response types:

  • Primitive types: string, int, bool
  • Objects: Reference to Go structs (e.g., UserResponse)
  • Arrays: array with item type
  • Generic objects: map[string]string, map[string]interface{}

Step 3: Generating Swagger Documentation

Once you've added all the necessary annotations, you can generate the Swagger documentation using the Gonyx CLI command.

Command

Run the following command in your project root:

gonyx generate swagger

Expected Output

When you run the command, you should see output similar to this:

2025/09/18 10:40:10 Initializing Config Provider ...
2025/09/18 10:40:10 DB Manager Package Initialized...
2025/09/18 10:40:10 Logger Manager Package Initialized...
2025/09/18 10:40:10 Initializing Cache Manager ...
2025/09/18 10:40:10 gRPC Manager Package Initialized...
2025/09/18 10:40:10 HTTP Manager Package Initialized...
Gonyx > Generating Swagger/OpenAPI documentation ...
Gonyx > Output directory: ./docs
Gonyx > Checking swag installation...
Gonyx > Swag not found, installing...
Gonyx > Swag installed successfully
Gonyx > Running 'swag init'...
Gonyx > 'swag init' completed successfully
Gonyx > Running 'swag fmt'...
Gonyx > 'swag fmt' completed successfully
Gonyx > Swagger documentation generated successfully in "./docs" ...

Generated Files

The command will create the following files in your docs/ directory:

  1. docs.go: Go package containing the swagger specification
  2. swagger.json: JSON format of the API specification
  3. swagger.yaml: YAML format of the API specification

Understanding the Process

The gonyx generate swagger command:

  1. Initializes: Sets up Gonyx components and dependencies
  2. Checks Dependencies: Verifies if the swag tool is installed
  3. Installs Tools: Automatically installs swag if not found
  4. Generates Documentation: Runs swag init to parse annotations and create documentation
  5. Formats Code: Runs swag fmt to format the generated Go code
  6. Outputs Files: Creates documentation files in the ./docs directory

Complete List of Supported Annotations

The annotations covered in this tutorial represent the most commonly used ones for basic API documentation. However, Swagger supports many more annotations for advanced use cases such as:

  • Security definitions (@securityDefinitions, @security)
  • File uploads (@Accept multipart/form-data)
  • Custom headers and authentication
  • Advanced parameter validation
  • Response headers
  • Deprecated endpoints
  • And much more...

For the complete and up-to-date list of all supported annotations, please refer to the official swaggo documentation:

📖 Complete Declarative Comments Format

This comprehensive reference includes:

  • All available annotations with detailed explanations
  • Advanced usage examples
  • Security configuration options
  • Custom type definitions
  • And other advanced features

Best Practices

1. Consistent Tagging

Use consistent tags to group related endpoints:

// @Tags User Management
// @Tags Authentication
// @Tags Orders

2. Comprehensive Descriptions

Provide clear, detailed descriptions:

// @Summary Create a new user account
// @Description Creates a new user account with email verification. Returns user details and sends welcome email.

3. Document All Responses

Include all possible response codes:

// @Success 201 {object} UserResponse "User created successfully"
// @Failure 400 {object} ErrorResponse "Invalid input data"
// @Failure 409 {object} ErrorResponse "Email already exists"
// @Failure 500 {object} ErrorResponse "Internal server error"

4. Use Proper Data Models

Define clear struct models for requests and responses:

type CreateUserRequest struct {
Email string `json:"email" binding:"required,email" example:"user@example.com"`
Name string `json:"name" binding:"required,min=2,max=50" example:"John Doe"`
Password string `json:"password" binding:"required,min=8" example:"securepassword123"`
}

5. Add Examples

Use struct tags to provide examples:

type User struct {
ID int `json:"id" example:"1"`
Email string `json:"email" example:"user@example.com"`
Name string `json:"name" example:"John Doe"`
IsActive bool `json:"is_active" example:"true"`
}

Troubleshooting

Common Issues

  1. Missing Annotations: Ensure all endpoints have proper Swagger annotations
  2. Incorrect Router Paths: Verify that @Router paths match your actual routes
  3. Import Issues: Make sure all referenced types are properly imported
  4. Format Errors: Run gonyx generate swagger to automatically format annotations

Regenerating Documentation

If you make changes to your annotations, simply run the command again:

gonyx generate swagger

The command will regenerate all documentation files with your latest changes.

Summary

You have successfully learned how to:

  1. ✅ Add API-level annotations to your app.go file
  2. ✅ Add route-specific annotations to your controller methods
  3. ✅ Generate Swagger documentation using gonyx generate swagger
  4. ✅ Understand the generated files and their purpose
  5. ✅ Apply best practices for comprehensive API documentation

Your Gonyx application now has professional, interactive API documentation that will help other developers understand and use your API effectively.

Next Steps

For more advanced Swagger features and customization options, refer to the Swagger/OpenAPI Specification.