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

  1. type HelloReq struct {
  2. g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
  3. Name string `v:"required" json:"name" dc:"User's name"`
  4. Age int `v:"required" json:"age" dc:"User's age"`
  5. }
  6. type HelloRes struct {
  7. Content string `json:"content" dc:"Response content"`
  8. }

We’ve added two important tags to the g.Meta field:

  • tags: Categorizes the API into logical groups
  • summary: Provides a brief description of the API endpoint

API Documentation - 图1info

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/net/ghttp"
  7. )
  8. type Response struct {
  9. Message string `json:"message" dc:"Response message"`
  10. Data interface{} `json:"data" dc:"Response payload"`
  11. }
  12. type HelloReq struct {
  13. g.Meta `path:"/" method:"get" tags:"Test" summary:"Hello world test case"`
  14. Name string `v:"required" json:"name" dc:"User's name"`
  15. Age int `v:"required" json:"age" dc:"User's age"`
  16. }
  17. type HelloRes struct {
  18. Content string `json:"content" dc:"Response content"`
  19. }
  20. type Hello struct{}
  21. func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
  22. res = &HelloRes{
  23. Content: fmt.Sprintf(
  24. "Hello %s! Your Age is %d",
  25. req.Name,
  26. req.Age,
  27. ),
  28. }
  29. return
  30. }
  31. func Middleware(r *ghttp.Request) {
  32. r.Middleware.Next()
  33. var (
  34. msg string
  35. res = r.GetHandlerResponse()
  36. err = r.GetError()
  37. )
  38. if err != nil {
  39. msg = err.Error()
  40. } else {
  41. msg = "OK"
  42. }
  43. r.Response.WriteJson(Response{
  44. Message: msg,
  45. Data: res,
  46. })
  47. }
  48. func main() {
  49. s := g.Server()
  50. s.Group("/", func(group *ghttp.RouterGroup) {
  51. group.Middleware(Middleware)
  52. group.Bind(
  53. new(Hello),
  54. )
  55. })
  56. s.SetOpenApiPath("/api.json")
  57. s.SetSwaggerPath("/swagger")
  58. s.SetPort(8000)
  59. s.Run()
  60. }

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:

  1. 2024-10-28 21:56:42.747 [INFO] pid[87280]: http server started listening on [:8000]
  2. 2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} swagger ui is serving at address: http://127.0.0.1:8000/swagger/
  3. 2024-10-28 21:56:42.747 [INFO] {d84db2976ea202187ba40f5d0657e4d7} openapi specification is serving at address: http://127.0.0.1:8000/api.json
  4. ADDRESS | METHOD | ROUTE | HANDLER | MIDDLEWARE
  5. ----------|--------|------------|-------------------------------------------------------|--------------------
  6. :8000 | GET | / | main.(*Hello).Say | main.Middleware
  7. ----------|--------|------------|-------------------------------------------------------|--------------------
  8. :8000 | ALL | /api.json | github.com/gogf/gf/v2/net/ghttp.(*Server).openapiSpec |
  9. ----------|--------|------------|-------------------------------------------------------|--------------------
  10. :8000 | ALL | /swagger/* | github.com/gogf/gf/v2/net/ghttp.(*Server).swaggerUI | HOOK_BEFORE_SERVE
  11. ----------|--------|------------|-------------------------------------------------------|--------------------

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. The HOOK_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:

alt text

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:

  1. Structured API definitions make APIs more maintainable, which is crucial for complex projects with many endpoints
  2. GoFrame’s automatic documentation generation creates standard OpenAPIv3 docs and Swagger UI with minimal effort, significantly reducing maintenance overhead and improving team collaboration