| 1 |
""" |
| 2 |
Example using marshmallow APISpec as base template for Flasgger specs |
| 3 |
and using the Swagger UI new style layout version 3 |
| 4 |
""" |
| 5 |
|
| 6 |
from flask import Flask, jsonify |
| 7 |
|
| 8 |
from flasgger import APISpec, Schema, Swagger, fields |
| 9 |
from apispec.ext.marshmallow import MarshmallowPlugin |
| 10 |
from apispec_webframeworks.flask import FlaskPlugin |
| 11 |
|
| 12 |
|
| 13 |
spec = APISpec( |
| 14 |
title='Flasger Petstore', |
| 15 |
version='1.0.10', |
| 16 |
openapi_version='2.0', |
| 17 |
plugins=[ |
| 18 |
FlaskPlugin(), |
| 19 |
MarshmallowPlugin(), |
| 20 |
], |
| 21 |
) |
| 22 |
|
| 23 |
app = Flask(__name__) |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
class CategorySchema(Schema): |
| 28 |
id = fields.Int() |
| 29 |
name = fields.Str(required=True) |
| 30 |
|
| 31 |
|
| 32 |
class PetSchema(Schema): |
| 33 |
category = fields.Nested(CategorySchema, many=True) |
| 34 |
name = fields.Str() |
| 35 |
|
| 36 |
|
| 37 |
@app.route('/random') |
| 38 |
def random_pet(): |
| 39 |
""" |
| 40 |
A cute furry animal endpoint. |
| 41 |
Get a random pet |
| 42 |
--- |
| 43 |
description: Get a random pet |
| 44 |
responses: |
| 45 |
200: |
| 46 |
description: A pet to be returned |
| 47 |
schema: |
| 48 |
$ref: '#/definitions/Pet' |
| 49 |
""" |
| 50 |
pet = {'category': [{'id': 1, 'name': 'rodent'}], 'name': 'Mickey'} |
| 51 |
return jsonify(PetSchema().dump(pet).data) |
| 52 |
|
| 53 |
|
| 54 |
template = spec.to_flasgger( |
| 55 |
app, |
| 56 |
definitions=[CategorySchema, PetSchema], |
| 57 |
paths=[random_pet] |
| 58 |
) |
| 59 |
|
| 60 |
""" |
| 61 |
optionally if using apispec.APISpec from original module |
| 62 |
you can do: |
| 63 |
|
| 64 |
from flasgger.utils import apispec_to_template |
| 65 |
template = apispec_to_template( |
| 66 |
app=app, |
| 67 |
spec=spec, |
| 68 |
definitions=[CategorySchema, PetSchema], |
| 69 |
paths=[random_pet] |
| 70 |
) |
| 71 |
|
| 72 |
""" |
| 73 |
|
| 74 |
|
| 75 |
app.config['SWAGGER'] = {'uiversion': 3} |
| 76 |
|
| 77 |
|
| 78 |
swag = Swagger(app, template=template) |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == '__main__': |
| 82 |
app.run(debug=True) |