| 1 | """ |
| 2 | In this example `openapi` version is used instead of `swagger` version. |
| 3 | """ |
| 4 | from flask import Flask, jsonify, request |
| 5 | from flasgger import Swagger, swag_from |
| 6 | |
| 7 | app = Flask(__name__) |
| 8 | swag = Swagger(app, config={ |
| 9 | 'headers': [], |
| 10 | 'specs': [ |
| 11 | { |
| 12 | 'endpoint': 'apispec', |
| 13 | 'route': '/apispec.json' |
| 14 | } |
| 15 | ], |
| 16 | 'openapi': '3.0.1' |
| 17 | }) |
| 18 | |
| 19 | |
| 20 | @swag.definition('Pet') |
| 21 | class Pet(object): |
| 22 | """ |
| 23 | Pet Object |
| 24 | --- |
| 25 | properties: |
| 26 | name: |
| 27 | type: string |
| 28 | """ |
| 29 | def __init__(self, name): |
| 30 | self.name = str(name) |
| 31 | |
| 32 | def dump(self): |
| 33 | return dict(vars(self).items()) |
| 34 | |
| 35 | |
| 36 | @app.route('/requestBody', methods=['POST']) |
| 37 | @swag_from() |
| 38 | def request_body_endpoint(): |
| 39 | """ |
| 40 | An endpoint for testing requestBody documentation. |
| 41 | --- |
| 42 | description: Post a request body |
| 43 | requestBody: |
| 44 | content: |
| 45 | application/json: |
| 46 | schema: |
| 47 | $ref: '#/components/schemas/Pet' |
| 48 | required: true |
| 49 | responses: |
| 50 | 200: |
| 51 | description: The posted request body |
| 52 | content: |
| 53 | application/json: |
| 54 | schema: |
| 55 | $ref: '#/components/schemas/Pet' |
| 56 | """ |
| 57 | return jsonify(request.json) |
| 58 | |
| 59 | |
| 60 | def test_swag(client, specs_data): |
| 61 | """ |
| 62 | This test is runs automatically in Travis CI |
| 63 | |
| 64 | :param client: Flask app test client |
| 65 | :param specs_data: {'url': {swag_specs}} for every spec in app |
| 66 | """ |
| 67 | print('SPEC+'+str(specs_data)) |
| 68 | for url, spec in specs_data.items(): |
| 69 | assert 'Pet' in spec['components']['schemas'] |
| 70 | |
| 71 | assert 'paths' in spec |
| 72 | paths = spec['paths'] |
| 73 | for path_def in paths.values(): |
| 74 | for method_def in path_def.values(): |
| 75 | assert 'requestBody' in method_def |
| 76 | |
| 77 | |
| 78 | if __name__ == '__main__': |
| 79 | app.run(debug=True) |