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):
接口文档中显示
热门推荐
数字时代的图片版权保卫战:你踩过哪些坑?
景甜肖像权胜诉:图片版权再敲警钟
如何避免摄影作品在微博上被侵权?
王一博再诉网店侵权案:肖像权保护新动向
《循环》研究证实:豆腐降低冠心病风险,营养价值全面解析
春日餐桌上的黄金搭档:豆腐虾仁的完美组合
教你挑选优质豆腐:从外观、气味到保存全攻略
南宁到北海自驾游:必打卡十大美景!
南宁到北海3天2晚冬季避寒游:银滩、涠洲岛、老街全打卡
Steam游戏被攻击怎么办,如何针对性的做好防护措施
浅析网络外挂的刑事司法规制
没打开的红酒,过了保质期还能喝吗?行家告诉你答案,别被误导了
手工揉面技巧大揭秘:轻松揉出完美面包面团
榴梿禁忌、营养逐个数:5大相克食物+3类高风险人士不宜进食
黑巧克力的好处和坏处 纯黑巧克力挑选及食用注意
食材搭配指南:解锁健康饮食的“魔法公式”
健康管理专业主要学什么-专业课程有哪些
为什么听到自己的录音会感觉羞耻?科学解释来了
物理学揭秘声波的奥秘
同时喜欢两个人:情感困境与解决之道
Michael的两难抉择:如何应对同时喜欢两人?
西安小众景点打卡:名人故居与历史遗迹
秋日限定!无锡环西蠡湖徒步攻略
从鼋头渚到灵山大佛:无锡马山37公里徒步全攻略
西安大雁塔与大唐芙蓉园:千年古塔与皇家园林的完美邂逅
北京中轴线:体现中华文明突出特性的重要标识
新会陈皮的功效与作用 新会陈皮现代应用方法有什么
陈皮的功效与作用:从舒缓情绪到调节血糖
2025 最新 70 句離職祝福語大全!搞笑/感性/英文短句 不同對象適用!
马桶高度多少影响舒适感,家居设计需谨慎