Generating API documentation with GoFrame
is straightforward. Let’s enhance our API definitions from the previous sections to create more comprehensive documentation.
Enhanced API Definitions
type HelloReq struct {
g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
Name string `v:"required" json:"name" dc:"User's name"`
Age int `v:"required" json:"age" dc:"User's age"`
}
type HelloRes struct {
Content string `json:"content" dc:"Response content"`
}
We’ve added two important tags to the g.Meta
field:
tags
: Categorizes the API into logical groupssummary
: Provides a brief description of the API endpoint
info
These tags are standard fields in the OpenAPIv3
specification. For a complete guide on API documentation generation and available tags, refer to the relevant section in our development manual.
Complete Implementation
main.go
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
type Response struct {
Message string `json:"message" dc:"Response message"`
Data interface{} `json:"data" dc:"Response payload"`
}
type HelloReq struct {
g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
Name string `v:"required" json:"name" dc:"User's name"`
Age int `v:"required" json:"age" dc:"User's age"`
}
type HelloRes struct {
Content string `json:"content" dc:"Response content"`
}
type Hello struct{}
func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
res = &HelloRes{
Content: fmt.Sprintf(
"Hello %s! Your Age is %d",
req.Name,
req.Age,
),
}
return
}
func Middleware(r *ghttp.Request) {
r.Middleware.Next()
var (
msg string
res = r.GetHandlerResponse()
err = r.GetError()
)
if err != nil {
msg = err.Error()
} else {
msg = "OK"
}
r.Response.WriteJson(Response{
Message: msg,
Data: res,
})
}
func main() {
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(Middleware)
group.Bind(
new(Hello),
)
})
s.SetOpenApiPath("/api.json")
s.SetSwaggerPath("/swagger")
s.SetPort(8000)
s.Run()
}
Key additions in this example:
s.SetOpenApiPath("/api.json")
enables OpenAPIv3 documentation generation at/api.json
s.SetSwaggerPath("/swagger")
enables the built-in Swagger UI at/swagger
(the UI can be customized - see our development manual for details)
Understanding OpenAPIv3
OpenAPIv3 is the industry standard for API documentation. It defines APIs in a machine-readable format (typically JSON) that can be consumed by various documentation tools like Swagger UI, Postman, and ApiFox.
Understanding Swagger
Swagger is a popular tool for visualizing and interacting with APIs. It supports multiple documentation formats, with OpenAPIv3 being the most common.
To use the built-in Swagger UI in this example, we need both OpenAPIv3 and Swagger UI enabled via the SetOpenApiPath
and SetSwaggerPath
methods respectively.
Running the Application
Console Output
When you run the application, you’ll see:
2024-10-28 21:56:42.747 [INFO] pid[87280]: http server started listening on [:8000]
2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} swagger ui is serving at address: http://127.0.0.1:8000/swagger/
2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} openapi specification is serving at address: http://127.0.0.1:8000/api.json
ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
----------|--------|------------|-------------------------------------------------------|--------------------
:8000 | GET | / | main.(*Hello).Say | main.Middleware
----------|--------|------------|-------------------------------------------------------|--------------------
:8000 | ALL | /api.json | github.com/gogf/gf/v2/net/ghttp.(*Server).openapiSpec |
----------|--------|------------|-------------------------------------------------------|--------------------
:8000 | ALL | /swagger/* | github.com/gogf/gf/v2/net/ghttp.(*Server).swaggerUI | HOOK_BEFORE_SERVE
----------|--------|------------|-------------------------------------------------------|--------------------
Notable changes in the output:
- A link to the Swagger UI at
http://127.0.0.1:8000/swagger/
- A link to the OpenAPI specification at
http://127.0.0.1:8000/api.json
- Two additional routes for Swagger and OpenAPI endpoints. The Swagger route uses the Server’s
HOOK
feature, which provides more flexible request interception than middleware. TheHOOK_BEFORE_SERVE
point used here is one of several predefined hook points (see the Web Server chapter in our manual for more details).
Exploring the Swagger UI
Visit http://127.0.0.1:8000/swagger/ to see your API documentation:
The UI shows:
- Our single API endpoint under the “Test” category with its description “Hello world test case”
- Detailed input/output structures including parameter types, validation rules (like required fields), and descriptions
Key Takeaways
We’ve learned two important concepts:
- Structured API definitions make APIs more maintainable, which is crucial for complex projects with many endpoints
- GoFrame’s automatic documentation generation creates standard OpenAPIv3 docs and Swagger UI with minimal effort, significantly reducing maintenance overhead and improving team collaboration