| 1 | """ |
| 2 | The simple example using declared definitions, and external static js/css. |
| 3 | """ |
| 4 | |
| 5 | from flask import Flask, jsonify |
| 6 | |
| 7 | from flasgger import Swagger |
| 8 | |
| 9 | app = Flask(__name__) |
| 10 | app.config['SWAGGER'] = { |
| 11 | 'title': 'Colors API' |
| 12 | } |
| 13 | swagger_config = Swagger.DEFAULT_CONFIG |
| 14 | swagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js' |
| 15 | swagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js' |
| 16 | swagger_config['jquery_js'] = '//unpkg.com/[email protected]/dist/jquery.min.js' |
| 17 | swagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css' |
| 18 | Swagger(app, config=swagger_config) |
| 19 | |
| 20 | @app.route('/colors/<palette>/') |
| 21 | def colors(palette): |
| 22 | """Example endpoint return a list of colors by palette |
| 23 | This is using docstring for specifications |
| 24 | --- |
| 25 | tags: |
| 26 | - colors |
| 27 | parameters: |
| 28 | - name: palette |
| 29 | in: path |
| 30 | type: string |
| 31 | enum: ['all', 'rgb', 'cmyk'] |
| 32 | required: true |
| 33 | default: all |
| 34 | description: Which palette to filter? |
| 35 | operationId: get_colors |
| 36 | consumes: |
| 37 | - application/json |
| 38 | produces: |
| 39 | - application/json |
| 40 | security: |
| 41 | colors_auth: |
| 42 | - 'write:colors' |
| 43 | - 'read:colors' |
| 44 | schemes: ['http', 'https'] |
| 45 | deprecated: false |
| 46 | externalDocs: |
| 47 | description: Project repository |
| 48 | url: http://github.com/rochacbruno/flasgger |
| 49 | definitions: |
| 50 | Palette: |
| 51 | type: object |
| 52 | properties: |
| 53 | palette_name: |
| 54 | type: array |
| 55 | items: |
| 56 | $ref: '#/definitions/Color' |
| 57 | Color: |
| 58 | type: string |
| 59 | responses: |
| 60 | 200: |
| 61 | description: A list of colors (may be filtered by palette) |
| 62 | schema: |
| 63 | $ref: '#/definitions/Palette' |
| 64 | examples: |
| 65 | rgb: ['red', 'green', 'blue'] |
| 66 | """ |
| 67 | all_colors = { |
| 68 | 'cmyk': ['cyan', 'magenta', 'yellow', 'black'], |
| 69 | 'rgb': ['red', 'green', 'blue'] |
| 70 | } |
| 71 | if palette == 'all': |
| 72 | result = all_colors |
| 73 | else: |
| 74 | result = {palette: all_colors.get(palette)} |
| 75 | |
| 76 | return jsonify(result) |
| 77 | |
| 78 | |
| 79 | def test_swag(client, specs_data): |
| 80 | """ |
| 81 | This test is runs automatically in Travis CI |
| 82 | |
| 83 | :param client: Flask app test client |
| 84 | :param specs_data: {'url': {swag_specs}} for every spec in app |
| 85 | """ |
| 86 | for url, spec in specs_data.items(): |
| 87 | assert 'Palette' in spec['definitions'] |
| 88 | assert 'Color' in spec['definitions'] |
| 89 | assert 'colors' in spec['paths']['/colors/{palette}/']['get']['tags'] |
| 90 | |
| 91 | |
| 92 | if __name__ == "__main__": |
| 93 | app.run(debug=True) |