brief introduction
Documentation is essential for API services.
Documents, however, are annoying, especially synchronous updates. If you choose handwritten documents, you often forget to update them.
Or in the early stages of high-speed development, there is no time to update the document.
A more popular way now is to use the document as a comment, to synchronize updates with the code.
Update in real time using auto-generated documents.
Another concept is that a document is a test so that it can be viewed as well as used. For API documents,
It's a huge convenience. With it, you don't have to look at the documentation anymore while you're driving the Postman experiment.
This is it. swagger.
swagger start
swagger provides many tools for creating API documents, especially the RESTful APIs standard.
This RESTful APIs standard, also known as OpenAPI Specification, currently has two specifications.
2.0 and 3.0.Most implementations are based on 2.0.
This project also uses the 2.0 specification.
Installing the swag tool also allows you to download precompiled binaries directly.
go get -u github.com/swaggo/swag/cmd/swag
Running swag init under the project root directory should create the docs directory.
swag init
Install swag-gin.
go get -u github.com/swaggo/gin-swagger go get -u github.com/swaggo/files
At this point, the dependencies have been installed and all that remains is documentation.
Write documentation
After all, it is a specification, or you should learn how to use it. If you are interested, you can see
Original specification.
Just look at the swag library documentation here.
Declarative Comments Format.
The main format is @key value, which is a key-value pair.
The final parse results in an entire json file.
Write a comment for the main function that defines the general information for the API.
// @title Apiserver API // @version 1.0 // @description This is a simple api server. // @contact.name coolcat // @contact.url http://coolcat.io/support // @contact.email help@coolcat.io // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @host 127.0.0.1:8081 // @BasePath /v1 // @securityDefinitions.apikey ApiKeyAuth // @in header // @name Authorization func main() { cmd.Execute() }
In the note above, there are four main parts which define:
- Title, Version Number, Description
- Contact Information
- license
- Security Definition
Update router.go to combine swagger with gin:
import { swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" // docs is generated by Swag CLI, you have to import it. _ "tzh.com/web/docs" } func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { ... // swagger document // The url pointing to API definition // /swagger/index.html url := ginSwagger.URL("/swagger/doc.json") g.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url)) ... }
The rest is to document each interface. For example, the documentation for the login interface is as follows:
// @Summary login // @Description login, get token // @Tags login // @Accept json // @Produce json // @Param body body model.UserModel true "User login"" // @Success 200 {object} model.Token "{"code":0,"message":"OK","data":{"token":"name"}}" // @Router /login [post] func Login(ctx *gin.Context) {
Here the basic properties of the interface are defined, including path, request type, output on success, output format, etc.
// @Summary Get Users // @Description Gets User Information from Database // @Tags user // @Accept json // @Produce json // @Security ApiKeyAuth // @Param id path uint64 true "user id in database" // @Success 200 {object} model.UserModel "{"code":0,"message":"OK","data": {}}" // @Router /user/{id} [get] func Get(ctx *gin.Context) {
The get interface has one more parameter @Security ApiKeyAuth than the login interface above to define the authentication method.
The authentication method ApiKeyAuth has already been defined in the main function's comment and can be specified directly here.
After each document update, you need to run swag init to update the docs directory.
After you start the server, you can access the API documentation on /swagger/index.html.
More documentation comments can be viewed in the source code.
Function
After the document is written, you need to run the swag init update, which can be defined in the Makefile file.
build: updoc go build -ldflags ${ldflags} ./ run: updoc go run -ldflags ${ldflags} ./ docker: updoc go run -ldflags ${ldflags} ./ -c ./conf/config_docker.yaml updoc: go mod download go get -u github.com/swaggo/swag/cmd/swag swag init
Run make run, then you can open http://localhost:8081/swagger/index.html in your browser and view the document.
Open http://localhost:8081/swagger/doc.json to view the generated JSON file.
With this json file, you can view the API documentation in other swagger gui s.
summary
swagger provides great convenience for writing documents. Good tools, but more importantly, persistence.
Code for current section
As Version v0.16.0