Integrating Swagger for API Documentation in Beego v2

Tanngo
2 min readJul 7, 2024

--

In today’s API development landscape, Swagger reigns supreme for creating clear and interactive documentation. Beego, a popular Go framework, seamlessly integrates with Swagger to streamline the documentation process.

So let go through the step to enable swagger for a beego project through a small example:

  1. Firstly, make sure beego is installed in your machine. If it is not installed, please run below command:
go get github.com/beego/beego/v2

2. Create a new project call swager_example by running below:

bee api swagger_example

As a result, you got below:

3. Run below command to install all the nescessary libraries

go get .
go mod vendor
go mod tidy

4. Add swagger by running below command:

bee run -gendoc=true -downdoc=true

5. Modify index.html in swagger folder to use swagger.json instead.

<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html
{
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}

*,
*:before,
*:after
{
box-sizing: inherit;
}

body
{
margin:0;
background: #fafafa;
}
</style>
</head>

<body>
<div id="swagger-ui"></div>

<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script>
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
// End Swagger UI call region

window.ui = ui;
};
</script>
</body>
</html>

6. Modify routers/router.go to add in the url by changing init function as below. Please note that do the same for /user url

func init() {
ns := beego.NewNamespace("/v1",
beego.NSNamespace("/object",
beego.NSInclude(
&controllers.ObjectController{},
),
beego.NSRouter("", &controllers.ObjectController{}, "get:GetAll"),
beego.NSRouter("/:objectId", &controllers.ObjectController{}, "get:Get"),
beego.NSRouter("", &controllers.ObjectController{}, "post:Post"),
beego.NSRouter("/:objectId", &controllers.ObjectController{}, "put:Put"),
beego.NSRouter("/:objectId", &controllers.ObjectController{}, "delete:Delete"),
),
beego.NSNamespace("/user",
beego.NSInclude(
&controllers.UserController{},
),
),
)
beego.AddNamespace(ns)
}

7. Browse the link: http://localhost:8080/swagger/ for seeing all the api documentation:

8. Example code can be found here: https://github.com/tanngo/swagger_beego_example

--

--