Debian Codegraph @

README.md

raw symbols SCIP
1 # Flasgger
2 ## Easy Swagger UI for your Flask API
3
4 [![Build Status](https://travis-ci.com/flasgger/flasgger.svg?branch=master)](https://travis-ci.com/flasgger/flasgger)
5 [![Code Health](https://landscape.io/github/rochacbruno/flasgger/master/landscape.svg?style=flat)](https://landscape.io/github/rochacbruno/flasgger/master)
6 [![Coverage Status](https://coveralls.io/repos/github/rochacbruno/flasgger/badge.svg?branch=master)](https://coveralls.io/github/rochacbruno/flasgger?branch=master)
7 [![PyPI](https://img.shields.io/pypi/v/flasgger.svg)](https://pypi.python.org/pypi/flasgger)
8 <a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=rochacbruno%40gmail%2ecom&amp;lc=BR&amp;item_name=Flasgger&amp;no_note=0&amp;currency_code=USD&amp;bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHostedGuest"><img alt='Donate with Paypal' src='http://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif' /></a>
9
10
11 ![flasgger](docs/flasgger.png)
12
13 Flasgger is a Flask extension to **extract [OpenAPI-Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object)** from all Flask views registered in your API.
14
15 Flasgger also comes with **[SwaggerUI](http://swagger.io/swagger-ui/) embedded** so you can access [http://localhost:5000/apidocs](localhost:5000/apidocs) and visualize and interact with your API resources.
16
17 Flasgger also **provides validation** of the incoming data, using the same specification it can validates if the data received as as a POST, PUT, PATCH is valid against the schema defined using **YAML**, **Python dictionaries** or **Marshmallow Schemas**.
18
19 Flasgger can work with simple function views or MethodViews using docstring as specification, or using `@swag_from` decorator to get specification from **YAML** or **dict** and also provides **SwaggerView** which can use **Marshmallow Schemas** as specification.
20
21 Flasgger is compatible with `Flask-RESTful` so you can use `Resources` and `swag` specifications together, take a look at [restful example.](examples/restful.py)
22
23 Flasgger also supports `Marshmallow APISpec` as base template for specification, if you are using APISPec from Marshmallow take a look at [apispec example.](examples/apispec_example.py)
24
25 Table of Contents
26 =================
27
28 * [Top Contributors](#top-contributors)
29 * [Examples and demo app](#examples-and-demo-app)
30 * [Docker](#docker)
31 * [Installation](#installation)
32 * [Getting started](#getting-started)
33 * [Using docstrings as specification](#using-docstrings-as-specification)
34 * [Using external YAML files](#using-external-yaml-files)
35 * [Using dictionaries as raw specs](#using-dictionaries-as-raw-specs)
36 * [Using Marshmallow Schemas](#using-marshmallow-schemas)
37 * [Using <strong>Flask RESTful</strong> Resources](#using-flask-restful-resources)
38 * [Auto-parsing external YAML docs and MethodViews](#auto-parsing-external-yaml-docs-and-methodviews)
39 * [Handling multiple http methods and routes for a single function](#handling-multiple-http-methods-and-routes-for-a-single-function)
40 * [Use the same data to validate your API POST body.](#use-the-same-data-to-validate-your-api-post-body)
41 * [Custom validation](#custom-validation)
42 * [Validation Error handling](#validation-error-handling)
43 * [Get defined schemas as python dictionaries](#get-defined-schemas-as-python-dictionaries)
44 * [HTML sanitizer](#html-sanitizer)
45 * [Swagger UI and templates](#swagger-ui-and-templates)
46 * [OpenAPI 3.0 Support](#openapi-30-support)
47 * [Externally loading Swagger UI and jQuery JS/CSS](#externally-loading-swagger-ui-and-jquery-jscss)
48 * [Initializing Flasgger with default data.](#initializing-flasgger-with-default-data)
49 * [Getting default data at runtime](#getting-default-data-at-runtime)
50 * [Behind a reverse proxy](#behind-a-reverse-proxy)
51 * [Customize default configurations](#customize-default-configurations)
52 * [Extracting Definitions](#extracting-definitions)
53 * [Python2 Compatibility](#python2-compatibility)
54
55 Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)
56
57 # Top Contributors
58
59 [![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/0)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/0)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/1)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/1)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/2)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/2)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/3)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/3)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/4)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/4)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/5)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/5)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/6)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/6)[![](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/images/7)](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/7)
60
61 # Examples and demo app
62
63 There are some [example applications](examples/) and you can also play with examples in [Flasgger demo app](http://flasgger.pythonanywhere.com/)
64
65 > NOTE: all the examples apps are also test cases and run automatically in Travis CI to ensure quality and coverage.
66
67 ## Docker
68
69 The examples and demo app can also be built and run as a Docker image/container:
70
71 ```
72 docker build -t flasgger .
73 docker run -it --rm -p 5000:5000 --name flasgger flasgger
74 ```
75 Then access the Flasgger demo app at http://localhost:5000 .
76
77 # Installation
78
79 > under your virtualenv do:
80
81 Ensure you have latest setuptools
82 ```
83 pip install -U setuptools
84 ```
85
86 then install beta version (recommended)
87
88 ```
89 pip install flasgger==0.9.7b2
90 ```
91
92 or (latest stable for legacy apps)
93
94 ```
95 pip install flasgger==0.9.5
96 ```
97
98 or (dev version)
99
100 ```
101 pip install https://github.com/flasgger/flasgger/tarball/master
102 ```
103
104 > NOTE: If you want to use **Marshmallow Schemas** you also need to run `pip install marshmallow apispec`
105
106 ## How to run tests
107
108 (You may see the command in [.travis.yml](./.travis.yml) for `before_install` part)
109
110 In your virtualenv:
111
112 ```
113 pip install -r requirements.txt
114 pip install -r requirements-dev.txt
115 make test
116 ```
117
118 # Getting started
119
120 ## Using docstrings as specification
121
122 Create a file called for example `colors.py`
123
124 ```python
125 from flask import Flask, jsonify
126 from flasgger import Swagger
127
128 app = Flask(__name__)
129 swagger = Swagger(app)
130
131 @app.route('/colors/<palette>/')
132 def colors(palette):
133 """Example endpoint returning a list of colors by palette
134 This is using docstrings for specifications.
135 ---
136 parameters:
137 - name: palette
138 in: path
139 type: string
140 enum: ['all', 'rgb', 'cmyk']
141 required: true
142 default: all
143 definitions:
144 Palette:
145 type: object
146 properties:
147 palette_name:
148 type: array
149 items:
150 $ref: '#/definitions/Color'
151 Color:
152 type: string
153 responses:
154 200:
155 description: A list of colors (may be filtered by palette)
156 schema:
157 $ref: '#/definitions/Palette'
158 examples:
159 rgb: ['red', 'green', 'blue']
160 """
161 all_colors = {
162 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
163 'rgb': ['red', 'green', 'blue']
164 }
165 if palette == 'all':
166 result = all_colors
167 else:
168 result = {palette: all_colors.get(palette)}
169
170 return jsonify(result)
171
172 app.run(debug=True)
173 ```
174
175 Now run:
176
177 ```
178 python colors.py
179 ```
180
181 And go to: [http://localhost:5000/apidocs/](http://localhost:5000/apidocs/)
182
183 You should get:
184
185 ![colors](docs/colors.png)
186
187 ## Using external YAML files
188
189 Save a new file `colors.yml`
190
191 ```yaml
192 Example endpoint returning a list of colors by palette
193 In this example the specification is taken from external YAML file
194 ---
195 parameters:
196 - name: palette
197 in: path
198 type: string
199 enum: ['all', 'rgb', 'cmyk']
200 required: true
201 default: all
202 definitions:
203 Palette:
204 type: object
205 properties:
206 palette_name:
207 type: array
208 items:
209 $ref: '#/definitions/Color'
210 Color:
211 type: string
212 responses:
213 200:
214 description: A list of colors (may be filtered by palette)
215 schema:
216 $ref: '#/definitions/Palette'
217 examples:
218 rgb: ['red', 'green', 'blue']
219 ```
220
221
222 lets use the same example changing only the view function.
223
224 ```python
225 from flasgger import swag_from
226
227 @app.route('/colors/<palette>/')
228 @swag_from('colors.yml')
229 def colors(palette):
230 ...
231 ```
232
233 If you do not want to use the decorator you can use the docstring `file:` shortcut.
234
235 ```python
236 @app.route('/colors/<palette>/')
237 def colors(palette):
238 """
239 file: colors.yml
240 """
241 ...
242 ```
243
244
245 ## Using dictionaries as raw specs
246
247 Create a Python dictionary as:
248
249 ```python
250 specs_dict = {
251 "parameters": [
252 {
253 "name": "palette",
254 "in": "path",
255 "type": "string",
256 "enum": [
257 "all",
258 "rgb",
259 "cmyk"
260 ],
261 "required": "true",
262 "default": "all"
263 }
264 ],
265 "definitions": {
266 "Palette": {
267 "type": "object",
268 "properties": {
269 "palette_name": {
270 "type": "array",
271 "items": {
272 "$ref": "#/definitions/Color"
273 }
274 }
275 }
276 },
277 "Color": {
278 "type": "string"
279 }
280 },
281 "responses": {
282 "200": {
283 "description": "A list of colors (may be filtered by palette)",
284 "schema": {
285 "$ref": "#/definitions/Palette"
286 },
287 "examples": {
288 "rgb": [
289 "red",
290 "green",
291 "blue"
292 ]
293 }
294 }
295 }
296 }
297 ```
298
299 Now take the same function and use the dict in the place of YAML file.
300
301 ```python
302 @app.route('/colors/<palette>/')
303 @swag_from(specs_dict)
304 def colors(palette):
305 """Example endpoint returning a list of colors by palette
306 In this example the specification is taken from specs_dict
307 """
308 ...
309 ```
310
311 ## Using Marshmallow Schemas
312
313 > FIRST: `pip install marshmallow apispec`
314
315 > USAGE #1: `SwaggerView`
316
317 ```python
318 from flask import Flask, jsonify
319 from flasgger import Swagger, SwaggerView, Schema, fields
320
321
322 class Color(Schema):
323 name = fields.Str()
324
325 class Palette(Schema):
326 pallete_name = fields.Str()
327 colors = fields.Nested(Color, many=True)
328
329 class PaletteView(SwaggerView):
330 parameters = [
331 {
332 "name": "palette",
333 "in": "path",
334 "type": "string",
335 "enum": ["all", "rgb", "cmyk"],
336 "required": True,
337 "default": "all"
338 }
339 ]
340 responses = {
341 200: {
342 "description": "A list of colors (may be filtered by palette)",
343 "schema": Palette
344 }
345 }
346
347 def get(self, palette):
348 """
349 Colors API using schema
350 This example is using marshmallow schemas
351 """
352 all_colors = {
353 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
354 'rgb': ['red', 'green', 'blue']
355 }
356 if palette == 'all':
357 result = all_colors
358 else:
359 result = {palette: all_colors.get(palette)}
360 return jsonify(result)
361
362 app = Flask(__name__)
363 swagger = Swagger(app)
364
365 app.add_url_rule(
366 '/colors/<palette>',
367 view_func=PaletteView.as_view('colors'),
368 methods=['GET']
369 )
370
371 app.run(debug=True)
372
373 ```
374
375 > USAGE #2: `Custom Schema from flasgger`
376
377 - `Body` - support all fields in marshmallow
378 - `Query` - support simple fields in marshmallow (Int, String and etc)
379 - `Path` - support only int and str
380
381 ```python
382 from flask import Flask, abort
383 from flasgger import Swagger, Schema, fields
384 from marshmallow.validate import Length, OneOf
385
386 app = Flask(__name__)
387 Swagger(app)
388
389 swag = {"swag": True,
390 "tags": ["demo"],
391 "responses": {200: {"description": "Success request"},
392 400: {"description": "Validation error"}}}
393
394
395 class Body(Schema):
396 color = fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
397
398 def swag_validation_function(self, data, main_def):
399 self.load(data)
400
401 def swag_validation_error_handler(self, err, data, main_def):
402 abort(400, err)
403
404
405 class Query(Schema):
406 color = fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
407
408 def swag_validation_function(self, data, main_def):
409 self.load(data)
410
411 def swag_validation_error_handler(self, err, data, main_def):
412 abort(400, err)
413
414 swag_in = "query"
415
416
417 @app.route("/color/<id>/<name>", methods=["POST"], **swag)
418 def index(body: Body, query: Query, id: int, name: str):
419 return {"body": body, "query": query, "id": id, "name": name}
420
421 if __name__ == "__main__":
422 app.run(debug=True)
423 ```
424
425
426 > NOTE: take a look at `examples/validation.py` for a more complete example.
427
428
429 > NOTE: when catching arguments in path rule always use explicit types, bad: ``/api/<username>`` good: ``/api/<string:username>``
430
431
432 ## Using **Flask RESTful** Resources
433
434 Flasgger is compatible with Flask-RESTful you only need to install `pip install flask-restful` and then:
435
436 ```python
437 from flask import Flask
438 from flasgger import Swagger
439 from flask_restful import Api, Resource
440
441 app = Flask(__name__)
442 api = Api(app)
443 swagger = Swagger(app)
444
445 class Username(Resource):
446 def get(self, username):
447 """
448 This examples uses FlaskRESTful Resource
449 It works also with swag_from, schemas and spec_dict
450 ---
451 parameters:
452 - in: path
453 name: username
454 type: string
455 required: true
456 responses:
457 200:
458 description: A single user item
459 schema:
460 id: User
461 properties:
462 username:
463 type: string
464 description: The name of the user
465 default: Steven Wilson
466 """
467 return {'username': username}, 200
468
469
470 api.add_resource(Username, '/username/<username>')
471
472 app.run(debug=True)
473 ```
474
475 ## Auto-parsing external YAML docs and `MethodView`s
476
477 Flasgger can be configured to auto-parse external YAML API docs. [Set a `doc_dir`](https://github.com/rochacbruno/flasgger/blob/aaef05c17cc559d01b7436211093463642eb6ae2/examples/parsed_view_func.py#L16) in your `app.config['SWAGGER']` and Swagger will load API docs by looking in `doc_dir` for YAML files stored by endpoint-name and method-name. For example, `'doc_dir': './examples/docs/'` and a file `./examples/docs/items/get.yml` will provide a Swagger doc for `ItemsView` method `get`.
478
479 Additionally, when using **Flask RESTful** per above, by passing `parse=True` when constructing `Swagger`, Flasgger will use `flask_restful.reqparse.RequestParser`, locate all `MethodView`s and parsed and validated data will be stored in `flask.request.parsed_data`.
480
481 ## Handling multiple http methods and routes for a single function
482
483 You can separate specifications by endpoint or methods
484
485 ```python
486 from flasgger.utils import swag_from
487
488 @app.route('/api/<string:username>', endpoint='with_user_name', methods=['PUT', 'GET'])
489 @app.route('/api/', endpoint='without_user_name')
490 @swag_from('path/to/external_file.yml', endpoint='with_user_name')
491 @swag_from('path/to/external_file_no_user_get.yml', endpoint='without_user_name', methods=['GET'])
492 @swag_from('path/to/external_file_no_user_put.yml', endpoint='without_user_name', methods=['PUT'])
493 def fromfile_decorated(username=None):
494 if not username:
495 return "No user!"
496 return jsonify({'username': username})
497 ```
498
499 And the same can be achieved with multiple methods in a `MethodView` or `SwaggerView` by
500 registering the `url_rule` many times. Take a look at `examples/example_app`
501
502
503 # Use the same data to validate your API POST body.
504
505 Setting `swag_from`'s _validation_ parameter to `True` will validate incoming data automatically:
506
507 ```python
508 from flasgger import swag_from
509
510 @swag_from('defs.yml', validation=True)
511 def post():
512 # if not validate returns ValidationError response with status 400
513 # also returns the validation message.
514 ```
515
516 Using `swagger.validate` annotation is also possible:
517
518 ```python
519 from flasgger import Swagger
520
521 swagger = Swagger(app)
522
523 @swagger.validate('UserSchema')
524 def post():
525 '''
526 file: defs.yml
527 '''
528 # if not validate returns ValidationError response with status 400
529 # also returns the validation message.
530 ```
531
532 Yet you can call `validate` manually:
533
534 ```python
535 from flasgger import swag_from, validate
536
537 @swag_from('defs.yml')
538 def post():
539 validate(request.json, 'UserSchema', 'defs.yml')
540 # if not validate returns ValidationError response with status 400
541 # also returns the validation message.
542 ```
543
544 It is also possible to define `validation=True` in `SwaggerView` and also use
545 `specs_dict` for validation.
546
547 Take a look at `examples/validation.py` for more information.
548
549 All validation options can be found at http://json-schema.org/latest/json-schema-validation.html
550
551 ### Custom validation
552
553 By default Flasgger will use [python-jsonschema](https://python-jsonschema.readthedocs.io/en/latest/)
554 to perform validation.
555
556 Custom validation functions are supported as long as they meet the requirements:
557 - take two, and only two, positional arguments:
558 - the data to be validated as the first; and
559 - the schema to validate against as the second argument
560 - raise any kind of exception when validation fails.
561
562 Any return value is discarded.
563
564
565 Providing the function to the Swagger instance will make it the default:
566
567 ```python
568 from flasgger import Swagger
569
570 swagger = Swagger(app, validation_function=my_validation_function)
571 ```
572
573 Providing the function as parameter of `swag_from` or `swagger.validate`
574 annotations or directly to the `validate` function will force it's use
575 over the default validation function for Swagger:
576
577 ```python
578 from flasgger import swag_from
579
580 @swag_from('spec.yml', validation=True, validation_function=my_function)
581 ...
582 ```
583
584 ```python
585 from flasgger import Swagger
586
587 swagger = Swagger(app)
588
589 @swagger.validate('Pet', validation_function=my_function)
590 ...
591 ```
592
593 ```python
594 from flasgger import validate
595
596 ...
597
598 validate(
599 request.json, 'Pet', 'defs.yml', validation_function=my_function)
600 ```
601
602 ### Validation Error handling
603
604 By default Flasgger will handle validation errors by aborting the
605 request with a 400 BAD REQUEST response with the error message.
606
607 A custom validation error handling function can be provided to
608 supersede default behavior as long as it meets the requirements:
609 - take three, and only three, positional arguments:
610 - the error raised as the first;
611 - the data which failed validation as the second; and
612 - the schema used in to validate as the third argument
613
614
615 Providing the function to the Swagger instance will make it the default:
616
617 ```python
618 from flasgger import Swagger
619
620 swagger = Swagger(app, validation_error_handler=my_handler)
621 ```
622
623 Providing the function as parameter of `swag_from` or `swagger.validate`
624 annotations or directly to the `validate` function will force it's use
625 over the default validation function for Swagger:
626
627 ```python
628 from flasgger import swag_from
629
630 @swag_from(
631 'spec.yml', validation=True, validation_error_handler=my_handler)
632 ...
633 ```
634
635 ```python
636 from flasgger import Swagger
637
638 swagger = Swagger(app)
639
640 @swagger.validate('Pet', validation_error_handler=my_handler)
641 ...
642 ```
643
644 ```python
645 from flasgger import validate
646
647 ...
648
649 validate(
650 request.json, 'Pet', 'defs.yml',
651 validation_error_handler=my_handler)
652 ```
653
654 Examples of use of a custom validation error handler function can be
655 found at [example validation_error_handler.py](examples/validation_error_handler.py)
656
657 # Get defined schemas as python dictionaries
658
659 You may wish to use schemas you defined in your Swagger specs as dictionaries
660 without replicating the specification. For that you can use the `get_schema`
661 method:
662
663 ```python
664 from flask import Flask, jsonify
665 from flasgger import Swagger, swag_from
666
667 app = Flask(__name__)
668 swagger = Swagger(app)
669
670 @swagger.validate('Product')
671 def post():
672 """
673 post endpoint
674 ---
675 tags:
676 - products
677 parameters:
678 - name: body
679 in: body
680 required: true
681 schema:
682 id: Product
683 required:
684 - name
685 properties:
686 name:
687 type: string
688 description: The product's name.
689 default: "Guarana"
690 responses:
691 200:
692 description: The product inserted in the database
693 schema:
694 $ref: '#/definitions/Product'
695 """
696 rv = db.insert(request.json)
697 return jsonify(rv)
698
699 ...
700
701 product_schema = swagger.get_schema('product')
702 ```
703
704 This method returns a dictionary which contains the Flasgger schema id,
705 all defined parameters and a list of required parameters.
706
707 # HTML sanitizer
708
709 By default Flasgger will try to sanitize the content in YAML definitions
710 replacing every ```\n``` with ```<br>``` but you can change this behaviour
711 setting another kind of sanitizer.
712
713 ```python
714 from flasgger import Swagger, NO_SANITIZER
715
716 app =Flask()
717 swagger = Swagger(app, sanitizer=NO_SANITIZER)
718 ```
719
720 You can write your own sanitizer
721
722 ```python
723 swagger = Swagger(app, sanitizer=lambda text: do_anything_with(text))
724 ```
725
726 There is also a Markdown parser available, if you want to be able to render
727 Markdown in your specs description use **MK_SANITIZER**
728
729
730 # Swagger UI and templates
731
732 You can override the `templates/flasgger/index.html` in your application and
733 this template will be the `index.html` for SwaggerUI. Use `flasgger/ui2/templates/index.html`
734 as base for your customization.
735
736 Flasgger supports Swagger UI versions 2 and 3, The version 3 is still experimental but you
737 can try setting `app.config['SWAGGER']['uiversion']`.
738
739 ```python
740 app = Flask(__name__)
741 app.config['SWAGGER'] = {
742 'title': 'My API',
743 'uiversion': 3
744 }
745 swagger = Swagger(app)
746
747 ```
748
749 # OpenAPI 3.0 Support
750
751 There is experimental support for OpenAPI 3.0 that should work when using SwaggerUI 3. To use OpenAPI 3.0, set `app.config['SWAGGER']['openapi']` to a version that the current SwaggerUI 3 supports such as `'3.0.2'`.
752
753 For an example of this that uses `callbacks` and `requestBody`, see the [callbacks example](examples/callbacks.py).
754
755 ## Externally loading Swagger UI and jQuery JS/CSS
756
757 Starting with Flasgger 0.9.2 you can specify external URL locations for loading the JavaScript and CSS for the Swagger and jQuery libraries loaded in the Flasgger default templates. If the configuration properties below are omitted, Flasgger will serve static versions it includes - these versions may be older than the current Swagger UI v2 or v3 releases.
758
759 The following example loads Swagger UI and jQuery versions from unpkg.com:
760
761 ```
762 swagger_config = Swagger.DEFAULT_CONFIG
763 swagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js'
764 swagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js'
765 swagger_config['jquery_js'] = '//unpkg.com/[email protected]/dist/jquery.min.js'
766 swagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css'
767 Swagger(app, config=swagger_config)
768 ```
769
770 # Initializing Flasgger with default data.
771
772 You can start your Swagger spec with any default data providing a template:
773
774 ```python
775 template = {
776 "swagger": "2.0",
777 "info": {
778 "title": "My API",
779 "description": "API for my data",
780 "contact": {
781 "responsibleOrganization": "ME",
782 "responsibleDeveloper": "Me",
783 "email": "[email protected]",
784 "url": "www.me.com",
785 },
786 "termsOfService": "http://me.com/terms",
787 "version": "0.0.1"
788 },
789 "host": "mysite.com", # overrides localhost:500
790 "basePath": "/api", # base bash for blueprint registration
791 "schemes": [
792 "http",
793 "https"
794 ],
795 "operationId": "getmyData"
796 }
797
798 swagger = Swagger(app, template=template)
799
800 ```
801
802 And then the template is the default data unless some view changes it. You
803 can also provide all your specs as template and have no views. Or views in
804 external APP.
805
806 ## Getting default data at runtime
807
808 Sometimes you need to get some data at runtime depending on dynamic values ex: you want to check `request.is_secure` to decide if `schemes` will be `https` you can do that by using `LazyString`.
809
810 ```py
811 from flask import Flask
812 from flasgger import, Swagger, LazyString, LazyJSONEncoder
813
814 app = Flask(__init__)
815
816 # Set the custom Encoder (Inherit it if you need to customize)
817 app.json_encoder = LazyJSONEncoder
818
819
820 template = dict(
821 info={
822 'title': LazyString(lambda: 'Lazy Title'),
823 'version': LazyString(lambda: '99.9.9'),
824 'description': LazyString(lambda: 'Hello Lazy World'),
825 'termsOfService': LazyString(lambda: '/there_is_no_tos')
826 },
827 host=LazyString(lambda: request.host),
828 schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')],
829 foo=LazyString(lambda: "Bar")
830 )
831 Swagger(app, template=template)
832
833 ```
834
835 The `LazyString` values will be evaluated only when `jsonify` encodes the value at runtime, so you have access to Flask `request, session, g, etc..` and also may want to access a database.
836
837 ## Behind a reverse proxy
838
839 Sometimes you're serving your swagger docs behind an reverse proxy (e.g. NGINX). When following the [Flask guidance](http://flask.pocoo.org/snippets/35/),
840 the swagger docs will load correctly, but the "Try it Out" button points to the wrong place. This can be fixed with the following code:
841
842 ```python
843 from flask import Flask, request
844 from flasgger import Swagger, LazyString, LazyJSONEncoder
845
846 app = Flask(__name__)
847 app.json_encoder = LazyJSONEncoder
848
849 template = dict(swaggerUiPrefix=LazyString(lambda : request.environ.get('HTTP_X_SCRIPT_NAME', '')))
850 swagger = Swagger(app, template=template)
851
852 ```
853
854 # Customize default configurations
855
856 Custom configurations such as a different specs route or disabling Swagger UI can be provided to Flasgger:
857
858 ```python
859 swagger_config = {
860 "headers": [
861 ],
862 "specs": [
863 {
864 "endpoint": 'apispec_1',
865 "route": '/apispec_1.json',
866 "rule_filter": lambda rule: True, # all in
867 "model_filter": lambda tag: True, # all in
868 }
869 ],
870 "static_url_path": "/flasgger_static",
871 # "static_folder": "static", # must be set by user
872 "swagger_ui": True,
873 "specs_route": "/apidocs/"
874 }
875
876 swagger = Swagger(app, config=swagger_config)
877
878 ```
879
880 ## Extracting Definitions
881
882 Definitions can be extracted when `id` is found in spec, example:
883
884 ```python
885 from flask import Flask, jsonify
886 from flasgger import Swagger
887
888 app = Flask(__name__)
889 swagger = Swagger(app)
890
891 @app.route('/colors/<palette>/')
892 def colors(palette):
893 """Example endpoint returning a list of colors by palette
894 ---
895 parameters:
896 - name: palette
897 in: path
898 type: string
899 enum: ['all', 'rgb', 'cmyk']
900 required: true
901 default: all
902 responses:
903 200:
904 description: A list of colors (may be filtered by palette)
905 schema:
906 id: Palette
907 type: object
908 properties:
909 palette_name:
910 type: array
911 items:
912 schema:
913 id: Color
914 type: string
915 examples:
916 rgb: ['red', 'green', 'blue']
917 """
918 all_colors = {
919 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
920 'rgb': ['red', 'green', 'blue']
921 }
922 if palette == 'all':
923 result = all_colors
924 else:
925 result = {palette: all_colors.get(palette)}
926
927 return jsonify(result)
928
929 app.run(debug=True)
930 ```
931
932 In this example you do not have to pass `definitions` but need to add `id` to
933 your schemas.
934
935 ## Python2 Compatibility
936
937 Version `0.9.5.*` will be the last verison that supports Python2.
938 Please direct discussions to [#399](https://github.com/flasgger/flasgger/issues/399).
939