flask openapi(swagger) doc generator
Project description
flask-siwadoc
flask-siwadoc:基于flask的接口文档自动生成库,告别手写接口文档
特性
flask-siwadoc是一个兼具数据校验和openapi(swagger)文档自动生成的项目
0、零配置
接入flask-siwadoc无需任何配置
1、数据校验
flask-siwadoc 站在巨人肩膀上,数据校验利用pydantic
强大的数据验证功能,支持请求查询参数和请求体参数的数据校验及转换功能。因此本项目同时依赖于pydantic。
2、接口文档自动生成
接口文档生成只需要简单初始化一个siwa=SiwaDoc(app)
,利用装饰器 siwa.doc()
修饰flask的视图函数,即可将该视图函数加入openapi的接口文档规范中。
3、ui切换
flask-siwadoc内置了redoc
、swagger
、rapidoc
等多种UI界面,通过参数/docs/?ui=xxx
切换
4、同时支持标签与分组
安装
pip install flask-siwadoc
快速开始
example 1
from flask import Flask
from flask_siwadoc import SiwaDoc
app = Flask(__name__)
siwa = SiwaDoc(app)
# or
# siwa.init_app(app)
@app.route("/hello", methods=["GET"])
@siwa.doc()
def hello():
return "hello siwadoc"
if __name__ == '__main__':
app.run()
运行后,访问 http://127.0.0.1:5000/docs 就可以看到openapi的文档页面
example 2:指定查询参数 query
from pydantic import BaseModel, Field
class QueryModel(BaseModel):
page: int = Field(default=1, title="current page number")
size: int = Field(default=20, title="size of page", ge=10, le=100)
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=['user'])
def users_list():
"""
user list
"""
return [{"username": "siwa", "id": 1}]
对于数查询接口,GET
请求需如果有查询参数,得益于pydantic强大的类型功能,我们只需要一个继承了BaseModel的自定义类,即可实现数据校验及转换。
如何在视图函数中使用该query
这个对象呢? 有两种方式
方式一:
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello():
print(request.query.keyword)
return "hello"
flask-siwadoc 将QueryModel的实例对象query
绑定到了flask的request对象上,不过对开发者来说使用并不友好,你没法知道它的类型是什么,意味着IDE无法用.
的方式调出该实例的属性。
方式二:(推荐方式)
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello(query: QueryModel):
print(query.keyword)
return "hello"
将query
变量作为视图函数的参数,flask-siwadoc 会自动将QueryModel实例对象赋值给query
变量,因为我们这里给query指定了类型声明,因此通过IDE可以很方便的调出实例属性。
下面的example3中的body参数原理也是类似的。
example3 :指定请求体 body
class LoginModel(BaseModel):
username: str
password: str
@app.route("/login", methods=["POST"])
@siwa.doc(body=LoginModel)
def login(body: LoginModel):
return {"username": body.username, "id": 1}
对于POST请求,请求体是基于application/json 类型, 会自动转换成LoginModel类型的对象,就可以用静态语言一样,通过点选的方式调出属性,例如 body.username
example4: 指定返回体 resp
class UserModel(BaseModel):
id: int
username: str
@app.route("/users/1", methods=["GET"])
@siwa.doc(resp=UserModel)
def users():
"""
user detail
"""
return {"username": "siwa", "id": 1}
example5: 指定标签分类 tags
项目中如果接口太多,我们可以对接口根据业务划分不同的模块标签来分类管理。
@siwa.doc(resp=UserModel, tags=["user"])
指定tags
参数,tags参数是一个列表,一个接口可支持多个标签。
example6: 指定分组 group
除了可以指定标签外,我们还可以指定分组
@app.route("/admin/login", methods=["POST"])
@siwa.doc(body=LoginModel, resp=UserModel, tags=['auth'], group='admin')
def admin_login(body: LoginModel):
return {"username": body.username, "id": 1}
example7:路径参数也支持文档化
针对参数,除了请求查询参数和请求体参数外,url路径中的参数,例如/users/<int(min=1):user_id>
同样支持,对于路径参数转api文档参数,不需要开发者做额外的处理,flask-siwadoc内部已经做了处理。
class QueryModel(BaseModel):
gender: str
class UpdatePasswordModel(BaseModel):
password: str
@app.route("/users/<int(min=1):user_id>", methods=["POST"])
@siwa.doc(query=QueryModel, body=UpdatePasswordModel, resp=UserModel)
def update_password(user_id):
"""
update password
"""
return {"username": "siwa", "id": user_id}
完整示例可参考 example.py
UI切换
文档默认使用redoc
进行渲染,你可以通过指定参数ui=swaggerui
显式文档。
http: // 127.0
.0
.1: 5000 / docs /?ui = swagger
扩展
如果数据校验报错,flask-siwadoc 会抛出异常flask_siwadoc.error.ValidationError
,ValidationError 继承自pydantic.ValidationError
例如:
class QueryModel(BaseModel):
keyword: str
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello(query: QueryModel):
print(query)
return "hello"
该接口中,keyword是必选的查询参数,如果url中没有keyword参数,就会抛出异常
raise ValidationError(e)
flask_siwadoc.error.ValidationError: 2 validation errors for Auth
username
field required (type=value_error.missing)
password
field required (type=value_error.missing)
我们需要通过使用flask的 errorhandler() 装饰函数来注册ValidationError
错误,这样错误异常就可以被validate_error
函数捕获,开发者可以给前端直接一个友好的错误响应体
@app.errorhandler(ValidationError)
def validate_error(e: ValidationError):
return dict(code=-1, msg="请求参数错误", error_info=e.errors()), 400
reference
- https://pydantic-docs.helpmanual.io/
- https://github.com/bauerji/flask-pydantic
- https://github.com/kemingy/flaskerk
任何问题欢迎发issue或者加我微信 lzjun567 交流,欢迎PR
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for flask_siwadoc-0.0.8-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | bfa7b784f1af4e7c9f518ee907be7aa4ab6e38ff8009b7a2b93fa0f5226a051c |
|
MD5 | 0727790348f0ccb4c263b0a2bceb2896 |
|
BLAKE2b-256 | 929a31d5008d64134f4aac7a12f7d77a9a05d8a05b476bc2f4b58ac271c2801d |