问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

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):
![](https://wy-static.wenxiaobai.com/chat-rag-image/2082278724370246612)
    '''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')
![](https://wy-static.wenxiaobai.com/chat-rag-image/7619122643169616907)
class Todo(Resource):

接口文档中显示

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号