| 1 | """ |
| 2 | Example using a dictionary as specification instead of YAML |
| 3 | """ |
| 4 | from flask import Flask, jsonify |
| 5 | |
| 6 | from flasgger import Swagger |
| 7 | from flasgger.utils import swag_from |
| 8 | |
| 9 | app = Flask(__name__) |
| 10 | app.config['SWAGGER'] = { |
| 11 | 'title': 'Colors API', |
| 12 | 'uiversion': 2 |
| 13 | } |
| 14 | swag = Swagger(app) |
| 15 | |
| 16 | |
| 17 | colors_spec = { |
| 18 | "tags": [ |
| 19 | "colors" |
| 20 | ], |
| 21 | "parameters": [ |
| 22 | { |
| 23 | "name": "palette", |
| 24 | "in": "path", |
| 25 | "type": "string", |
| 26 | "enum": [ |
| 27 | "all", |
| 28 | "rgb", |
| 29 | "cmyk" |
| 30 | ], |
| 31 | "required": True, |
| 32 | "default": "all", |
| 33 | "description": "Which palette to filter?" |
| 34 | } |
| 35 | ], |
| 36 | "operationId": "get_colors", |
| 37 | "consumes": [ |
| 38 | "application/json" |
| 39 | ], |
| 40 | "produces": [ |
| 41 | "application/json" |
| 42 | ], |
| 43 | "security": { |
| 44 | "colors_auth": [ |
| 45 | "write:colors", |
| 46 | "read:colors" |
| 47 | ] |
| 48 | }, |
| 49 | "schemes": [ |
| 50 | "http", |
| 51 | "https" |
| 52 | ], |
| 53 | "deprecated": False, |
| 54 | "externalDocs": { |
| 55 | "description": "Project repository", |
| 56 | "url": "http://github.com/rochacbruno/flasgger" |
| 57 | }, |
| 58 | "definitions": { |
| 59 | "Palette": { |
| 60 | "type": "object", |
| 61 | "properties": { |
| 62 | "palette_name": { |
| 63 | "type": "array", |
| 64 | "items": { |
| 65 | "$ref": "#/definitions/Color" |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | }, |
| 70 | "Color": { |
| 71 | "type": "string" |
| 72 | } |
| 73 | }, |
| 74 | "responses": { |
| 75 | "200": { |
| 76 | "description": "A list of colors (may be filtered by palette)", |
| 77 | "schema": { |
| 78 | "$ref": "#/definitions/Palette" |
| 79 | }, |
| 80 | "examples": { |
| 81 | "rgb": [ |
| 82 | "red", |
| 83 | "green", |
| 84 | "blue" |
| 85 | ] |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | |
| 92 | @app.route('/colors/<palette>/') |
| 93 | @swag_from(colors_spec) |
| 94 | def colors(palette): |
| 95 | """ |
| 96 | Example using a dictionary as specification |
| 97 | This is the description |
| 98 | You can also set 'summary' and 'description' in |
| 99 | specs_dict |
| 100 | --- |
| 101 | # values here overrides the specs dict |
| 102 | deprecated: true |
| 103 | """ |
| 104 | all_colors = { |
| 105 | 'cmyk': ['cyan', 'magenta', 'yellow', 'black'], |
| 106 | 'rgb': ['red', 'green', 'blue'] |
| 107 | } |
| 108 | if palette == 'all': |
| 109 | result = all_colors |
| 110 | else: |
| 111 | result = {palette: all_colors.get(palette)} |
| 112 | |
| 113 | return jsonify(result) |
| 114 | |
| 115 | if __name__ == "__main__": |
| 116 | app.run(debug=True) |