使用apidoc管理RESTful风格Flask项目接口文档
程序员文章站
2022-03-31 21:15:18
...
使用apidoc管理RESTful风格Flask项目接口文档
1.安装nodejs
sudo apt-get install nodejs
sudo apt install nodejs-legacy
sudo apt install npm
2.安装apidoc
npm install apidoc -g
3.Flask扩展包安装
pip install flask-apidoc
4.添加扩展包到Flask项目
- 依赖环境
flask>=0.10.1
flask_script>=2.0.5
- manage.py项目启动脚本配置
from views import app
from flask_apidoc.commands import GenerateApiDoc
from flask_script import Manager
manager = Manager(app)
manager.add_command('apidoc', GenerateApiDoc())
if __name__ == "__main__":
manager.run()
- apidoc.json配置
必须在项目根目录下建立apidoc.json配置文件
{
"name": "Flask REST API",
"version": "1.0.0",
"description": "A Flask REST API example",
"title": "A Flask REST API example",
"url" : "http://localhost:5000"
}
- 视图函数文档注释说明示例
# -*- coding: utf-8 -*-
from flask import Flask
from flask_apidoc import ApiDoc
app = Flask(__name__)
doc = ApiDoc(app=app)
@app.route('/users', methods=['POST'])
def register():
"""
@api {post} /api/v1.0/users 注册
@apiVersion 1.0.0
@apiName register_user
@apiGroup Users
@apiParam {String} mobile (必须) 用户手机号
@apiParam {String} password (必须) 用户密码
@apiParam {String} sms_code (必须) 用户短信验证码
@apiParamExample {json} Request-Example:
{
mobile: "13970512239",
password: "123456",
sms_code: "907896"
}
@apiSuccess (回参) {int} user_id 用户注册id
@apiSuccess (回参) {String} name 用户昵称
@apiSuccess (回参) {String} mobile 用户注册手机号
@apiSuccess (回参) {String} avatar 用户头像地址
@apiSuccess (回参) {String} create_time 用户创建时间
@apiSuccessExample {json} Success-Response:
{
"errno":0,
"errmsg":"注册成功!",
"data": {
"user_id": 1,
"name": "lynnyq",
"mobile": "13813888888",
"avatar": "http://p3ifu3dwc.bkt.clouddn.com/FjuAwxmcCtiud_nOZ",
"create_time": "2010-1-1 12:12:12"
}
}
@apiErrorExample {json} Error-Response:
{
"errno":4001,
"errmsg":"数据库查询错误!"
}
"""
pass
5.生成RESTful风格接口文档
python manage.py apidoc
文档默认生成在项目根目录下的static/docs文件夹下