使用Flask和apispec构建和文档化REST API
项目描述
flask-apispec 是一个用于在Flask中构建REST API的轻量级工具。 flask-apispec 使用 webargs 进行请求解析,使用 marshmallow 进行响应格式化,并使用 apispec 自动生成Swagger标记。您可以使用 flask-apispec 与纯Flask或功能更全面的框架,如 Flask-RESTful。
安装
pip install flask-apispec
快速入门
from flask import Flask
from flask_apispec import use_kwargs, marshal_with
from marshmallow import Schema
from webargs import fields
from .models import Pet
app = Flask(__name__)
class PetSchema(Schema):
class Meta:
fields = ('name', 'category', 'size')
@app.route('/pets')
@use_kwargs({'category': fields.Str(), 'size': fields.Str()})
@marshal_with(PetSchema(many=True))
def get_pets(**kwargs):
return Pet.query.filter_by(**kwargs)
flask-apispec 与基于函数和类的视图一起工作
from flask import make_response
from flask_apispec.views import MethodResource
class PetResource(MethodResource):
@marshal_with(PetSchema)
def get(self, pet_id):
return Pet.query.filter(Pet.id == pet_id).one()
@use_kwargs(PetSchema)
@marshal_with(PetSchema, code=201)
def post(self, **kwargs):
return Pet(**kwargs)
@use_kwargs(PetSchema)
@marshal_with(PetSchema)
def put(self, pet_id, **kwargs):
pet = Pet.query.filter(Pet.id == pet_id).one()
pet.__dict__.update(**kwargs)
return pet
@marshal_with(None, code=204)
def delete(self, pet_id):
pet = Pet.query.filter(Pet.id == pet_id).one()
pet.delete()
return make_response('', 204)
flask-apispec 为您的视图函数和类生成Swagger标记。默认情况下,Swagger JSON在 /swagger/ 提供,Swagger-UI在 /swagger-ui/ 提供。
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from flask_apispec.extension import FlaskApiSpec
app.config.update({
'APISPEC_SPEC': APISpec(
title='pets',
version='v1',
plugins=[MarshmallowPlugin()],
),
'APISPEC_SWAGGER_URL': '/swagger/',
})
docs = FlaskApiSpec(app)
docs.register(get_pets)
docs.register(PetResource)
文档
注意
flask-apispec 强烈受到 Flask-RESTful 和 Flask-RESTplus 的启发,但试图以更大的灵活性和更少的代码提供类似的功能。