当前位置:网站首页>Super efficient! The secret of swagger Yapi
Super efficient! The secret of swagger Yapi
2022-07-06 08:46:00 【Baidu geek said】
Reading guide : Believe in both front-end and back-end development , Are more or less tortured by interface documents . The front end often complains that the interface document given by the back end is inconsistent with the actual situation . The back end also thinks that writing and maintaining interface documents will cost a lot of energy , Often too late to update . In fact, whether the front end calls the back end , Back end calls back end , All expect a good interface document . But over time , Version of the iteration , Interface documents are easy to lose track of code , There will also be former students who leave without clearly handing over the interface documents , Leave a heavy and complex project , It's very difficult to chew it again , No less than writing it all over again . Therefore, it is not enough to regulate everyone only through coercion . We studied Swagger To Yapi How to get through .
With it , We can write code every time , Just modify the comments by the way , And then submit ,Yapi Our interface documents can be automatically changed on .The full text 8199 word , Estimated reading time 21 minute .
One 、Swagger brief introduction
Swagger Is a specification and complete framework , Used to generate 、 describe 、 Invocation and visualization RESTful style Web service . You just need to define the interface and the interface related information according to its specifications . Re pass Swagger A series of derived projects and tools , You can generate various formats of interface documents , Generate multi language client and server code , And online interface debugging page and so on .
such , If you follow the new development model , When developing new or iterative versions , Just update Swagger Description file , Can automatically generate interface documents and client server code , Call end code 、 Consistency of server code and interface documents .
Two 、Swagger build
The following steps are based on the successful operation of go On the environment .
stay go-swagger The most complete tutorial can be seen on the official tutorial , Those who have the ability can go directly to the official tutorial .
2.1► install
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-4piURlCx-1656992344963)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a304fd5c53de4f8298464c58c33271e4~tplv-k3u1fbpfcp-zoom-1.image)]
All the above download methods are feasible , But in order to be compatible with all our situations , So choose this , Download the code directly .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-f8C8L4D6-1656992344963)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/93120313144e41758d2c1a7d3eef4b48~tplv-k3u1fbpfcp-zoom-1.image)]
Simplify the order , Actually, I did two things :
1、clone go-swagger Code for ;
2、 hold swaager add GOROOT.
mkdir DownLoad
cd DownLoad
git clone https://github.com/go-swagger/go-swagger
cd DownLoad/go-swagger-master/cmd/swagger/
go install .
To see if it works :
[[email protected] /]$ swagger -h
Usage:
swagger [OPTIONS] <command>
Swagger tries to support you as best as possible when building APIs.
It aims to represent the contract of your API with a language agnostic description of your application in json or yaml.
Application Options:
-q, --quiet silence logs
--log-output=LOG-FILE redirect logs to file
Help Options:
-h, --help Show this help message
Available commands:
diff diff swagger documents
expand expand $ref fields in a swagger spec
flatten flattens a swagger document
generate generate go code
init initialize a spec document
mixin merge swagger documents
serve serve spec and docs
validate validate the swagger document
version print the version
2.2► build
- This part is all about swagger Usage of , Let's start with the simplest , Interface notes , Copy the comments above the sample to the top of the interface :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-biifRvYP-1656992344964)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/252a79cd0c6547938d5c105831a35ea7~tplv-k3u1fbpfcp-zoom-1.image)]
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-NnpRjYHl-1656992344964)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fe2f08407cfa436e9451ea678c6e5528~tplv-k3u1fbpfcp-zoom-1.image)]
- Sample document comments :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-PEXczxzo-1656992344965)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6943c92064fc4c11a6d41a72246c5655~tplv-k3u1fbpfcp-zoom-1.image)]
function swagger, Generate interface document
command :swagger generate spec -o ./swagger.json
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-nErJZBN2-1656992344965)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c0e3553f3ce64d84960d1d60752ec9af~tplv-k3u1fbpfcp-zoom-1.image)]
start-up swagger service , Enter the interface document page
command :swagger serve --no-open swagger.json
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-1AZhDTt0-1656992344966)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7ecba32724404a169127ffe095f40bdf~tplv-k3u1fbpfcp-zoom-1.image)]
3、 ... and 、Swagger standard
Swagger The specification and usage of notes are as follows .
3.1►swagger:meta
brief introduction :swagger:meta It's all you have API Summary , We use it to form our API Introduction at the beginning of the document .
// Go-Swagger API.(title)
//
// This is our test API (description)
//
// Terms Of Service:
// there are no TOS at this moment, use at your own risk we take no responsibility
//
// Schemes: http, https
// Host: localhost
// BasePath: /go-swagger/test
// Version: 0.0.1
// License: MIT http://opensource.org/licenses/MIT
// Contact: Zhubangzheng<[email protected]> [email protected]
//
// Consumes:
// - application/json
// - application/xml
//
// Produces:
// - application/json
// - application/xml
//
// Security:
// - api_key:
//
// SecurityDefinitions:
// api_key:
// type: apiKey
// name: KEY
// in: header
// oauth2:
// type: oauth2
// authorizationUrl: /oauth2/auth
// tokenUrl: /oauth2/token
// in: header
// scopes:
// bar: foo
// flow: accessCode
//
// Extensions:
// x-meta-value: value
// x-meta-array:
// - value1
// - value2
// x-meta-array-obj:
// - name: obj
// value: field
//
// swagger:meta
package test
Be careful : The end of the comment swagger:meta and package There can be no blank line , Otherwise, it cannot be swagger distinguish .
Note usage :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-ccQDm6cA-1656992344966)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2c5b04207262417180e116b72019de52~tplv-k3u1fbpfcp-zoom-1.image)]
3.2►swagger:route
swagger:route Is the main annotation parameter , It's your single API Interface details .
Format :swagger:route [method] [path pattern] [tag1 tag2 tag3] [operation id]
[method] and [path pattern] Mandatory , hinder [tag] It's up to you , The first is your current interface tag, Then consider adding others . final [operation id] Is the only identification of your method , If it is only used as an interface document, you can leave it blank , But it is used as a method name in many places . For example, methods for client generation .
// ServeAPI serves the API for this record store
func ServeAPI(host, basePath string, schemes []string) error {
// swagger:route GET /{id}/checkout SwaggerTest swagger_test_checkout
//
// Swagger Test interface
//
// be used for Swagger test
//
// Consumes:
// - application/json
// - application/x-protobuf
//
// Produces:
// - application/json
// - application/x-protobuf
//
// Schemes: http, https, ws, wss
//
// Deprecated: true
//
// Security:
// api_key:
// oauth: read, write
//
// Responses:
// default: genericError
// 200: someResponse
// 422: validationError
mountItem("GET", basePath+"/{id}/checkout", nil)
}
Response And defined later swagger:response Corresponding .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-5jdIWDYy-1656992344967)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/13d52f23da8044bdb78d48e7c61792e8~tplv-k3u1fbpfcp-zoom-1.image)]
3.3►swagger:patameters
swagger:parameters It is the Parameter annotation of the interface
Format :swagger:parameters [operationid1 operationid2],parameters adopt [operation id] and route binding .
There are many ways to play parameters , But it's basically useless. You can check it in the official documents swagger:parameters.
Because we mainly use GET、POST, The official website only introduces GET Method , Intranet and extranet for swagger:parameters Annotated POST There is little introduction to the usage of , So here we introduce GET and POST The main way to play .
// swagger:parameters swagger_test_checkout
type SwaggerTest struct {
// SwaggerTest Interface test parameters 1 (description)
// required: true( Whether must )
// in: query( Where the parameter is located )
ID uinat64 `json:"id"`
}
a key :GET Methodical in notes Connectable query、header、cookie、path , It depends on different situations .
The above is our statement GET Necessary comments for the parameters of , Everything else is unnecessary , Here's the picture , You can add .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-DDTZT71d-1656992344967)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fad0e4e0a2da43f1a87e9f948035c4b5~tplv-k3u1fbpfcp-zoom-1.image)]
- POST:
// swagger:parameters swagger_test_checkout
type SwaggerTest struct {
// SwaggerTest Interface test parameters 1 (description)
// required: true( Whether must )
// in: formData( Where the parameter is located )
ID uinat64 `json:"id"`
}
POST Method , The position of the parameter is not body, In other words, No in:body, But to use in:formData, This format is imported into yapi Then it will appear in body in , And in the local swagger ui In order to display correctly . Another thing to note is that it is recommended to swagger:route Situated Consumes Set to multipart/form-data, namely :
// ServeAPI serves the API for this record store
func ServeAPI(host, basePath string, schemes []string) error {
// swagger:route GET /{id}/checkout SwaggerTest swagger_test_checkout
//
// Swagger Test interface
//
// be used for Swagger test
//
// Consumes:
// multipart/form-data
//
// ......
mountItem("GET", basePath+"/{id}/checkout", nil)
}
Format :swagger:response [response name] ,response adopt [response name] and route As defined in response binding .
The usage of response comments and parameters is basically the same swagger:response, There is no need to repeat here , Direct example .
// A ValidationError is an error that is used when the required input fails validation.
// swagger:response validationError
type ValidationError struct {
// The error message
// in: body
Body struct {
// The validation message
//
// Required: true
// Example: Expected type int
Message string
// An optional field name to which this validation applies
FieldName string
}
}
a key : The above usage is response Basic usage , But in fact, it does not conform to the definition of the internal structure of many companies , So the following will talk about the real flexible and practical usage .
1、swagger:response It can appear on any structure . There is no need to find our response layer , Or not even response Layer of , Instead, each interface defines a special response, Finally, use it uniformly interface Handle , This leads us to add swagger Extremely difficult .
for example :
// SwaggerTestResponse
// swagger:response test_res
type SwaggerTestResponse struct {
// The error message
// in: body
Body struct {
// The validation message
//
// Required: true
// Example: Expected type int
Message string
// An optional field name to which this validation applies
FieldName string
}
}
Be careful :: Must strictly follow the format ,Response A... Is nested under the structure Body Structure , That is to say, if it is our historical project , You have to Response Wrap another layer . for example : This is a project that is being used Response return , We add swagger:response, The only one following it id,test, Use at the return of the interface .
// Test
// swagger:response old_api_resp
type OldAPIRes struct {
// Test
// in: body
ID uint64
Name string
Time string
}
// ServeAPI serves the API for this record store
func ServeAPI(host, basePath string, schemes []string) error {
// swagger:route GET /{id}/checkout SwaggerTest swagger_test_checkout
//
// Swagger Test interface
//
// be used for Swagger test
//
// Consumes:
// - multipart/form-data
// Schemes: http
// Responses:
// 200: old_api_resp
mountItem("GET", basePath+"/{id}/checkout", nil)
}
And then we generate swagger.json, It is found that all parameters are defined in header Next , These return parameters should actually be located in body in , Otherwise, it cannot be swagger ui and yapi distinguish .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-CQXOPIf4-1656992344968)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c384534c5a66463280a32acfd24f3541~tplv-k3u1fbpfcp-zoom-1.image)]
let me put it another way swagger Of in:body Only recognize the nested structures in the structure , In order to cater to swagger Identification requirements , We transform the structure , Change to the following way , Can be identified in body In the .
// Test
// swagger:response old_api_resp
type OldAPIRes struct {
// Test
// in: body
Body struct {
ID uint64
Name string
Time string
}
}
The above way of writing is actually very inconvenient , All interfaces Response Add one more layer below Body, This is not reasonable ,Swagger Just notes , Should not intrude code , Unless the original structure is like this , Otherwise, the above format is not recommended .
2、 premium swagger:model: Solved the above pain points , Truly flexible and easy to use .
swagger:model It's actually a swagger standard , The usage is very flexible , Detailed usage will be introduced later , Here we propose to use model solve response Methods .
Response Modification of comments :
// swagger:model old_api_resp
type OldAPIRes struct {
ID uint64
Name string
Time string
}
Route Note modification :
// ServeAPI serves the API for this record store
func ServeAPI(host, basePath string, schemes []string) error {
// swagger:route GET /{id}/checkout SwaggerTest swagger_test_checkout
//
// Swagger Test interface
//
// be used for Swagger test
//
// Consumes:
// - multipart/form-data
// Produces:
// - application/json
// Schemes: http
// Responses:
// 200: body:old_api_resp
mountItem("GET", basePath+"/{id}/checkout", nil)
Command to change ,-m It's a scan model:
swagger generate spec -m -o ./swagger.json
To regenerate the , And then it's done .
Four 、Swagger-Yapi
Yapi An efficient 、 Easy to use 、 Powerful API Management platform .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-lzgrxZxB-1656992344968)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/4479efc1adfe402fba0f74079e2aa4c5~tplv-k3u1fbpfcp-zoom-1.image)]
Why should I get through Swagger To Yapi Well ? The reason is simple .Swagger Of SwaggerUI Far from it Yapi Comprehensive function , and Yapi Can support importing Swagger.json Format interface document ,Swagger Convenience and Yapi The comprehensiveness of , We combine the two , So as to achieve better results .
4.1►Nginx build
After the above steps, we should have generated our interface locally Swagger.json, and Yapi Manual import and automatic import are supported .
Manual import :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-WzaKqnC3-1656992344968)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/91f8073560e94f54811ae223052c88e3~tplv-k3u1fbpfcp-zoom-1.image)]
Automatic import :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-SfrXTQet-1656992344969)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/93430b105fa24700b5aafeb682572ebd~tplv-k3u1fbpfcp-zoom-1.image)]
What we need ? What we need is every time Swagger After the update ,Yapi Will automatically update our interface , Then we naturally need to use Yapi Automatic import of , So we only need to build one on our own machine Nginx To do static file proxy , Can achieve .
Download and install nginx:
sudo yum install nginx -y
Check... After installation :
rpm -qa | grep nginx
start-up nginx
sudo systemctl start nginx
or
sudo service nginx start
see nginx state
sudo systemctl status nginx
or
sudo service nginx status
4.2► Proxy file
Get into nginx Catalog
cd /etc/nginx/
stay conf.d Add a new port to the directory that requires proxy
data The mapped directory depends on your actual situation , namely swagger.json Depending on the location of the directory .
cd conf.d/
vim yapi.conf
server {
listen 8888;
server_name localhost;
location /data/ {
alias '/home/work/Swagger/swagger-yapi/swagger-json/';
}
}
restart nginx
sudo systemctl restart nginx
or
sudo service nginx restart
4.3►Yapi Automatic synchronization
ip Corresponding to your own machine ip.
ip The address can be viewed through the following command :
hostname -i
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-TYuJ7lNo-1656992344969)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/e7cfeb16d4c445ceb0644ed01ecc0d3c~tplv-k3u1fbpfcp-zoom-1.image)]
If prompted :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-JQfcNGLu-1656992344970)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c24abb50d815460a8bfe1220f7d1e91d~tplv-k3u1fbpfcp-zoom-1.image)]
Explain that the path is not right , You can enter the address into the browser to access , Adjust yourself to the right .
5、 ... and 、 Conclusion
Swagger There are many other uses , Light is through swagger -h Commands can see many uses , And its annotation usage also has many , There are also different ways of writing for different languages . Empathy ,Yapi As a powerful API The management platform is the same. It has many uses , Like online mock Interface, etc. . This article is just a quick start swagger To yapi Methods , After the passage is built , You can find more usage by yourself .
————————END————————
Recommended reading :
Baidu live iOS SDK Platformized output transformation
Baidu APP be based on Pipeline as Code Continuous integration practice of
Go Language use MySQL Common fault analysis and countermeasures
Analysis on the wallet system architecture of Baidu trading platform
Wide table based data modeling application
边栏推荐
- C語言雙指針——經典題型
- 广州推进儿童友好城市建设,将探索学校周边200米设安全区域
- Double pointeur en langage C - - modèle classique
- Guangzhou will promote the construction of a child friendly city, and will explore the establishment of a safe area 200 meters around the school
- Roguelike游戏成破解重灾区,如何破局?
- 704 binary search
- 深度剖析C语言指针
- LeetCode:劍指 Offer 42. 連續子數組的最大和
- Rviz仿真时遇到机器人瞬间回到世界坐标原点的问题及可能原因
- LeetCode:剑指 Offer 03. 数组中重复的数字
猜你喜欢
可变长参数
[embedded] cortex m4f DSP Library
Double pointeur en langage C - - modèle classique
Variable length parameter
Cisp-pte practice explanation
个人电脑好用必备软件(使用过)
JS inheritance method
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
被破解毁掉的国产游戏之光
MySQL learning records 12jdbc operation transactions
随机推荐
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
Shift Operators
同一局域网的手机和电脑相互访问,IIS设置
电脑清理,删除的系统文件
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
有效提高软件产品质量,就找第三方软件测评机构
MySQL learning record 10getting started with JDBC
MySQL learning record 07 index (simple understanding)
延迟初始化和密封类
On the inverse order problem of 01 knapsack problem in one-dimensional state
vb.net 随窗口改变,缩放控件大小以及保持相对位置
JS native implementation shuttle box
Unified ordering background interface product description Chinese garbled
查看局域网中电脑设备
pytorch训练好的模型在加载和保存过程中的问题
marathon-envs项目环境配置(强化学习模仿参考动作)
Visual implementation and inspection of visdom
LeetCode:劍指 Offer 42. 連續子數組的最大和
Image, CV2 read the conversion and size resize change of numpy array of pictures
win10系统中的截图,win+prtSc保存位置