Flask-RESTX 生成 Swagger 文档

Swagger API 文档是自动生成的,可从您的 API 的根 URL 获取。@api.doc() 您可以使用装饰器配置文档。

基本配置

默认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):

接口文档中显示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值