Debian Codegraph @

PKG-INFO

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