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/')
@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)
基础教程参考前面这篇https://www.cnblogs.com/yoyoketang/p/16656220.html
项目结构使用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('/')
@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)
启动服务
>flask run
访问http://127.0.0.1:5000/
,会看到namespaces 命名空间(相当于一个模块)
点开todos,可以看到常见的5个接口
接口的注释部分,如下
def get(self):
'''List all tasks'''
在文档上显示标题
装饰器 @api.doc()
可以添加接口的详细描述
@api.doc(description='接口描述,描述接口在什么场景使用 list_todos')
@api.marshal_list_with(todo)
def get(self):
'''List all tasks'''
post请求参数(payload)通过@api.expect()
自动生成, response返回参数通过@api.marshal_with
自动生成
@api.expect(todo)
@api.marshal_with(todo, code=201)
def post(self):
'''Create a new task'''
url上的路径参数描述,使用@api.param()
装饰器描述整个类下的接口,都带有公共参数id
@api.param('id', 'The task identifier')
class Todo(Resource):
针对单个接口使用 @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):