Flask-RESTX 生成 Swagger 文档
创作时间:
作者:
@小白创作中心
Flask-RESTX 生成 Swagger 文档
引用
CSDN
1.
https://m.blog.csdn.net/m0_37886429/article/details/137911986
本文将详细介绍如何使用Flask-RESTX生成Swagger文档。通过本文,你将学习到如何配置基本的Swagger文档、组织项目结构、以及如何为API添加详细的接口描述。
Swagger API 文档是自动生成的,可从您的 API 的根 URL 获取。您可以使用装饰器配置文档。
基本配置
默认flask-restx提供Swagger UI文档,从 API 的根 URL 提供
from flask import Flask
from flask_restx import Api, Resource, fields
app = Flask(__name__)
api = Api(app, version='1.0', title='Sample API',
description='A sample API',
)
@api.route('/my-resource/<id>')
@api.doc(params={'id': 'An ID'})
class MyResource(Resource):
def get(self, id):
return {}
@api.response(403, 'Not Authorized')
def post(self, id):
api.abort(403)
if __name__ == '__main__':
app.run(debug=True)
项目结构
项目结构使用namespaces 命名空间。这是一个示例目录结构:
project/
├── app.py
├── core
│ ├── __init__.py
│ ├── utils.py
│ └── ...
└── apis
├── __init__.py
├── auth.py
├── ...
└── blog.py
apis/init.py中内容:
from flask import Flask
from flask_restx import Api
api = Api(
title='yoyo API 接口文档',
version='1.0',
description='API 文档描述',
# All API metadatas
)
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
# ... 加载配置和数据库部分省略
from .auth import api as ns1
from .blog import api as ns2
api.add_namespace(ns1)
api.add_namespace(ns2)
# ...
api.init_app(app)
return app
app.py 中启动服务:
from apis import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
blog.py 代码参考的规范文档代码,做了一些稍微修改:
from flask import Flask
from flask_restx import Api, Resource, fields, Namespace
from werkzeug.middleware.proxy_fix import ProxyFix
api = Namespace('todos', description='TODO operations')
todo = api.model('Todo', {
'id': fields.Integer(readonly=True, description='The task unique identifier'),
'task': fields.String(required=True, description='The task details')
})
class TodoDAO(object):
def __init__(self):
self.counter = 0
self.todos = []
def get(self, id):
for todo in self.todos:
if todo['id'] == id:
return todo
api.abort(404, "Todo {} doesn't exist".format(id))
def create(self, data):
todo = data
todo['id'] = self.counter = self.counter + 1
self.todos.append(todo)
return todo
def update(self, id, data):
todo = self.get(id)
todo.update(data)
return todo
def delete(self, id):
todo = self.get(id)
self.todos.remove(todo)
DAO = TodoDAO()
DAO.create({'task': 'Build an API'})
DAO.create({'task': '?????'})
DAO.create({'task': 'profit!'})
@api.route('/')
class TodoList(Resource):
'''Shows a list of all todos, and lets you POST to add new tasks'''
@api.doc(description='接口描述,描述接口在什么场景使用 list_todos')
@api.marshal_list_with(todo)
def get(self):
'''List all tasks'''
return DAO.todos
@api.doc(description='create_todo')
@api.expect(todo)
@api.marshal_with(todo, code=201)
def post(self):
'''Create a new task'''
return DAO.create(api.payload), 201
@api.route('/<int:id>')
@api.response(404, 'Todo not found')
@api.param('id', 'The task identifier')
class Todo(Resource):
'''Show a single todo item and lets you delete them'''
@api.doc('get_todo')
@api.marshal_with(todo)
def get(self, id):
'''Fetch a given resource'''
return DAO.get(id)
@api.doc(description='delete_todo')
@api.response(204, 'Todo deleted')
def delete(self, id):
'''Delete a task given its identifier'''
DAO.delete(id)
return '', 204
@api.expect(todo)
@api.marshal_with(todo)
def put(self, id):
'''Update a task given its identifier'''
return DAO.update(id, api.payload)
Swagger 文档
启动服务:
flask run
访问 http://127.0.0.1:5000/,会看到namespaces 命名空间(相当于一个模块)。点开todos,可以看到常见的5个接口。
接口名称
接口的注释部分,如下:
def get(self):
'''List all tasks'''
在文档上显示标题。
description描述
装饰器
@api.doc()
可以添加接口的详细描述:
@api.doc(description='接口描述,描述接口在什么场景使用 list_todos')
@api.marshal_list_with(todo)
def get(self):
'''List all tasks'''
payload参数
post请求参数(payload)通过
@api.expect()
自动生成, response返回参数通过
@api.marshal_with
自动生成:
@api.expect(todo)
@api.marshal_with(todo, code=201)
def post(self):

'''Create a new task'''
params 参数
url上的路径参数描述,使用
@api.param()
装饰器描述整个类下的接口,都带有公共参数id
针对单个接口使用
@api.doc()
加
params 参数
@api.doc(description='create_todo',
params={
'id': '描述参数'
})
def get(self, id):
状态码描述
@api.response()
@api.response(404, 'Todo not found')
@api.param('id', 'The task identifier')

class Todo(Resource):
接口文档中显示
热门推荐
10部全球经典动画电影榜单:评分9.0以上,多部获奥斯卡
痛风为什么不能喝酒,看完这篇文章你就明白了
European Radiology:深度学习在肺结节检测与分割中的应用
扬州的古城墙与历史建筑游
用AI工具链从零到一制作MV,创作小白必看
家里滴滴答答?教你快速揪出漏水元凶!
人生是没有意义的,需要自己去创造意义
聚酯纤维面料真的好吗?了解3个特性,重点看4个优点和3个缺点
sus316与304哪个更好(316和304不锈钢对比)
一天吃五个香蕉的后果
东南名邑,古色今香!余姚市历史文化遗存在城市更新中加速“活”起来
2024年必读的5本小说:科幻末世脑洞等无限流爽文
什么是锂聚合物电池?原理、优缺点及应用前景全解析
动产所有权的法律解析与保护措施探讨
DeepSeek使用遇“服务器繁忙”?八大实用解决方案帮你轻松应对
青岛十大特色名小吃,品味海滨城市的独特风味
如何正确注销微信小程序以避免数据泄露?
小孩子不吃饭能吃什么?这三类食物可以做替代
【男士衬衫】男士衬衫尺码对照表 男士衬衫如何选购搭配
金融资产是什么
《弟子规》教育活动设计方案:从理论到实践的完整指南
高中地理重点知识点:环境与环境问题
手枪在战场上究竟有什么作用?军官真的拿着手枪战斗吗?基本不会
取得进出口资质的五大步骤:全方位指南
人生规划指南:从目标设定到行动落地
月柱国印流霞,命运多变,财富与灾难并存
绿萝在室内的生长(让你的家更有生命力)
脖子长扁平疣怎么去除掉
安置房土地出让金怎么计算?买卖是否受法律保护?
怎么在电子税务局查询个人所得税申报明细表