# Flasgger
## Easy Swagger UI for your Flask API
[](https://travis-ci.com/flasgger/flasgger)
[](https://landscape.io/github/rochacbruno/flasgger/master)
[](https://coveralls.io/github/rochacbruno/flasgger?branch=master)
[](https://pypi.python.org/pypi/flasgger)
<a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rochacbruno%40gmail%2ecom&lc=BR&item_name=Flasgger&no_note=0&currency_code=USD&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>

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.
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.
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**.
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.
Flasgger is compatible with `Flask-RESTful` so you can use `Resources` and `swag` specifications together, take a look at [restful example.](examples/restful.py)
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)
Table of Contents
=================
* [Top Contributors](#top-contributors)
* [Examples and demo app](#examples-and-demo-app)
* [Docker](#docker)
* [Installation](#installation)
* [Getting started](#getting-started)
* [Using docstrings as specification](#using-docstrings-as-specification)
* [Using external YAML files](#using-external-yaml-files)
* [Using dictionaries as raw specs](#using-dictionaries-as-raw-specs)
* [Using Marshmallow Schemas](#using-marshmallow-schemas)
* [Using <strong>Flask RESTful</strong> Resources](#using-flask-restful-resources)
* [Auto-parsing external YAML docs and MethodViews](#auto-parsing-external-yaml-docs-and-methodviews)
* [Handling multiple http methods and routes for a single function](#handling-multiple-http-methods-and-routes-for-a-single-function)
* [Use the same data to validate your API POST body.](#use-the-same-data-to-validate-your-api-post-body)
* [Custom validation](#custom-validation)
* [Validation Error handling](#validation-error-handling)
* [Get defined schemas as python dictionaries](#get-defined-schemas-as-python-dictionaries)
* [HTML sanitizer](#html-sanitizer)
* [Swagger UI and templates](#swagger-ui-and-templates)
* [OpenAPI 3.0 Support](#openapi-30-support)
* [Externally loading Swagger UI and jQuery JS/CSS](#externally-loading-swagger-ui-and-jquery-jscss)
* [Initializing Flasgger with default data.](#initializing-flasgger-with-default-data)
* [Getting default data at runtime](#getting-default-data-at-runtime)
* [Behind a reverse proxy](#behind-a-reverse-proxy)
* [Customize default configurations](#customize-default-configurations)
* [Extracting Definitions](#extracting-definitions)
* [Python2 Compatibility](#python2-compatibility)
Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)
# Top Contributors
[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/0)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/1)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/2)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/3)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/4)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/5)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/6)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/7)
# Examples and demo app
There are some [example applications](examples/) and you can also play with examples in [Flasgger demo app](http://flasgger.pythonanywhere.com/)
> NOTE: all the examples apps are also test cases and run automatically in Travis CI to ensure quality and coverage.
## Docker
The examples and demo app can also be built and run as a Docker image/container:
```
docker build -t flasgger .
docker run -it --rm -p 5000:5000 --name flasgger flasgger
```
Then access the Flasgger demo app at http://localhost:5000 .
# Installation
> under your virtualenv do:
Ensure you have latest setuptools
```
pip install -U setuptools
```
then install beta version (recommended)
```
pip install flasgger==0.9.7b2
```
or (latest stable for legacy apps)
```
pip install flasgger==0.9.5
```
or (dev version)
```
pip install https://github.com/flasgger/flasgger/tarball/master
```
> NOTE: If you want to use **Marshmallow Schemas** you also need to run `pip install marshmallow apispec`
## How to run tests
(You may see the command in [.travis.yml](./.travis.yml) for `before_install` part)
In your virtualenv:
```
pip install -r requirements.txt
pip install -r requirements-dev.txt
make test
```
# Getting started
## Using docstrings as specification
Create a file called for example `colors.py`
```python
from flask import Flask, jsonify
from flasgger import Swagger
app = Flask(__name__)
swagger = Swagger(app)
@app.route('/colors/<palette>/')
def colors(palette):
"""Example endpoint returning a list of colors by palette
This is using docstrings for specifications.
---
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
definitions:
Palette:
type: object
properties:
palette_name:
type: array
items:
$ref: '#/definitions/Color'
Color:
type: string
responses:
200:
description: A list of colors (may be filtered by palette)
schema:
$ref: '#/definitions/Palette'
examples:
rgb: ['red', 'green', 'blue']
"""
all_colors = {
'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
if palette == 'all':
result = all_colors
else:
result = {palette: all_colors.get(palette)}
return jsonify(result)
app.run(debug=True)
```
Now run:
```
python colors.py
```
And go to: [http://localhost:5000/apidocs/](http://localhost:5000/apidocs/)
You should get:

## Using external YAML files
Save a new file `colors.yml`
```yaml
Example endpoint returning a list of colors by palette
In this example the specification is taken from external YAML file
---
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
definitions:
Palette:
type: object
properties:
palette_name:
type: array
items:
$ref: '#/definitions/Color'
Color:
type: string
responses:
200:
description: A list of colors (may be filtered by palette)
schema:
$ref: '#/definitions/Palette'
examples:
rgb: ['red', 'green', 'blue']
```
lets use the same example changing only the view function.
```python
from flasgger import swag_from
@app.route('/colors/<palette>/')
@swag_from('colors.yml')
def colors(palette):
...
```
If you do not want to use the decorator you can use the docstring `file:` shortcut.
```python
@app.route('/colors/<palette>/')
def colors(palette):
"""
file: colors.yml
"""
...
```
## Using dictionaries as raw specs
Create a Python dictionary as:
```python
specs_dict = {
"parameters": [
{
"name": "palette",
"in": "path",
"type": "string",
"enum": [
"all",
"rgb",
"cmyk"
],
"required": "true",
"default": "all"
}
],
"definitions": {
"Palette": {
"type": "object",
"properties": {
"palette_name": {
"type": "array",
"items": {
"$ref": "#/definitions/Color"
}
}
}
},
"Color": {
"type": "string"
}
},
"responses": {
"200": {
"description": "A list of colors (may be filtered by palette)",
"schema": {
"$ref": "#/definitions/Palette"
},
"examples": {
"rgb": [
"red",
"green",
"blue"
]
}
}
}
}
```
Now take the same function and use the dict in the place of YAML file.
```python
@app.route('/colors/<palette>/')
@swag_from(specs_dict)
def colors(palette):
"""Example endpoint returning a list of colors by palette
In this example the specification is taken from specs_dict
"""
...
```
## Using Marshmallow Schemas
> FIRST: `pip install marshmallow apispec`
> USAGE #1: `SwaggerView`
```python
from flask import Flask, jsonify
from flasgger import Swagger, SwaggerView, Schema, fields
class Color(Schema):
name = fields.Str()
class Palette(Schema):
pallete_name = fields.Str()
colors = fields.Nested(Color, many=True)
class PaletteView(SwaggerView):
parameters = [
{
"name": "palette",
"in": "path",
"type": "string",
"enum": ["all", "rgb", "cmyk"],
"required": True,
"default": "all"
}
]
responses = {
200: {
"description": "A list of colors (may be filtered by palette)",
"schema": Palette
}
}
def get(self, palette):
"""
Colors API using schema
This example is using marshmallow schemas
"""
all_colors = {
'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
if palette == 'all':
result = all_colors
else:
result = {palette: all_colors.get(palette)}
return jsonify(result)
app = Flask(__name__)
swagger = Swagger(app)
app.add_url_rule(
'/colors/<palette>',
view_func=PaletteView.as_view('colors'),
methods=['GET']
)
app.run(debug=True)
```
> USAGE #2: `Custom Schema from flasgger`
- `Body` - support all fields in marshmallow
- `Query` - support simple fields in marshmallow (Int, String and etc)
- `Path` - support only int and str
```python
from flask import Flask, abort
from flasgger import Swagger, Schema, fields
from marshmallow.validate import Length, OneOf
app = Flask(__name__)
Swagger(app)
swag = {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
class Body(Schema):
color = fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
def swag_validation_function(self, data, main_def):
self.load(data)
def swag_validation_error_handler(self, err, data, main_def):
abort(400, err)
class Query(Schema):
color = fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
def swag_validation_function(self, data, main_def):
self.load(data)
def swag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in = "query"
@app.route("/color/<id>/<name>", methods=["POST"], **swag)
def index(body: Body, query: Query, id: int, name: str):
return {"body": body, "query": query, "id": id, "name": name}
if __name__ == "__main__":
app.run(debug=True)
```
> NOTE: take a look at `examples/validation.py` for a more complete example.
> NOTE: when catching arguments in path rule always use explicit types, bad: ``/api/<username>`` good: ``/api/<string:username>``
## Using **Flask RESTful** Resources
Flasgger is compatible with Flask-RESTful you only need to install `pip install flask-restful` and then:
```python
from flask import Flask
from flasgger import Swagger
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
swagger = Swagger(app)
class Username(Resource):
def get(self, username):
"""
This examples uses FlaskRESTful Resource
It works also with swag_from, schemas and spec_dict
---
parameters:
- in: path
name: username
type: string
required: true
responses:
200:
description: A single user item
schema:
id: User
properties:
username:
type: string
description: The name of the user
default: Steven Wilson
"""
return {'username': username}, 200
api.add_resource(Username, '/username/<username>')
app.run(debug=True)
```
## Auto-parsing external YAML docs and `MethodView`s
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`.
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`.
## Handling multiple http methods and routes for a single function
You can separate specifications by endpoint or methods
```python
from flasgger.utils import swag_from
@app.route('/api/<string:username>', endpoint='with_user_name', methods=['PUT', 'GET'])
@app.route('/api/', endpoint='without_user_name')
@swag_from('path/to/external_file.yml', endpoint='with_user_name')
@swag_from('path/to/external_file_no_user_get.yml', endpoint='without_user_name', methods=['GET'])
@swag_from('path/to/external_file_no_user_put.yml', endpoint='without_user_name', methods=['PUT'])
def fromfile_decorated(username=None):
if not username:
return "No user!"
return jsonify({'username': username})
```
And the same can be achieved with multiple methods in a `MethodView` or `SwaggerView` by
registering the `url_rule` many times. Take a look at `examples/example_app`
# Use the same data to validate your API POST body.
Setting `swag_from`'s _validation_ parameter to `True` will validate incoming data automatically:
```python
from flasgger import swag_from
@swag_from('defs.yml', validation=True)
def post():
# if not validate returns ValidationError response with status 400
# also returns the validation message.
```
Using `swagger.validate` annotation is also possible:
```python
from flasgger import Swagger
swagger = Swagger(app)
@swagger.validate('UserSchema')
def post():
'''
file: defs.yml
'''
# if not validate returns ValidationError response with status 400
# also returns the validation message.
```
Yet you can call `validate` manually:
```python
from flasgger import swag_from, validate
@swag_from('defs.yml')
def post():
validate(request.json, 'UserSchema', 'defs.yml')
# if not validate returns ValidationError response with status 400
# also returns the validation message.
```
It is also possible to define `validation=True` in `SwaggerView` and also use
`specs_dict` for validation.
Take a look at `examples/validation.py` for more information.
All validation options can be found at http://json-schema.org/latest/json-schema-validation.html
### Custom validation
By default Flasgger will use [python-jsonschema](https://python-jsonschema.readthedocs.io/en/latest/)
to perform validation.
Custom validation functions are supported as long as they meet the requirements:
- take two, and only two, positional arguments:
- the data to be validated as the first; and
- the schema to validate against as the second argument
- raise any kind of exception when validation fails.
Any return value is discarded.
Providing the function to the Swagger instance will make it the default:
```python
from flasgger import Swagger
swagger = Swagger(app, validation_function=my_validation_function)
```
Providing the function as parameter of `swag_from` or `swagger.validate`
annotations or directly to the `validate` function will force it's use
over the default validation function for Swagger:
```python
from flasgger import swag_from
@swag_from('spec.yml', validation=True, validation_function=my_function)
...
```
```python
from flasgger import Swagger
swagger = Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
```
```python
from flasgger import validate
...
validate(
request.json, 'Pet', 'defs.yml', validation_function=my_function)
```
### Validation Error handling
By default Flasgger will handle validation errors by aborting the
request with a 400 BAD REQUEST response with the error message.
A custom validation error handling function can be provided to
supersede default behavior as long as it meets the requirements:
- take three, and only three, positional arguments:
- the error raised as the first;
- the data which failed validation as the second; and
- the schema used in to validate as the third argument
Providing the function to the Swagger instance will make it the default:
```python
from flasgger import Swagger
swagger = Swagger(app, validation_error_handler=my_handler)
```
Providing the function as parameter of `swag_from` or `swagger.validate`
annotations or directly to the `validate` function will force it's use
over the default validation function for Swagger:
```python
from flasgger import swag_from
@swag_from(
'spec.yml', validation=True, validation_error_handler=my_handler)
...
```
```python
from flasgger import Swagger
swagger = Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
```
```python
from flasgger import validate
...
validate(
request.json, 'Pet', 'defs.yml',
validation_error_handler=my_handler)
```
Examples of use of a custom validation error handler function can be
found at [example validation_error_handler.py](examples/validation_error_handler.py)
# Get defined schemas as python dictionaries
You may wish to use schemas you defined in your Swagger specs as dictionaries
without replicating the specification. For that you can use the `get_schema`
method:
```python
from flask import Flask, jsonify
from flasgger import Swagger, swag_from
app = Flask(__name__)
swagger = Swagger(app)
@swagger.validate('Product')
def post():
"""
post endpoint
---
tags:
- products
parameters:
- name: body
in: body
required: true
schema:
id: Product
required:
- name
properties:
name:
type: string
description: The product's name.
default: "Guarana"
responses:
200:
description: The product inserted in the database
schema:
$ref: '#/definitions/Product'
"""
rv = db.insert(request.json)
return jsonify(rv)
...
product_schema = swagger.get_schema('product')
```
This method returns a dictionary which contains the Flasgger schema id,
all defined parameters and a list of required parameters.
# HTML sanitizer
By default Flasgger will try to sanitize the content in YAML definitions
replacing every ```\n``` with ```<br>``` but you can change this behaviour
setting another kind of sanitizer.
```python
from flasgger import Swagger, NO_SANITIZER
app =Flask()
swagger = Swagger(app, sanitizer=NO_SANITIZER)
```
You can write your own sanitizer
```python
swagger = Swagger(app, sanitizer=lambda text: do_anything_with(text))
```
There is also a Markdown parser available, if you want to be able to render
Markdown in your specs description use **MK_SANITIZER**
# Swagger UI and templates
You can override the `templates/flasgger/index.html` in your application and
this template will be the `index.html` for SwaggerUI. Use `flasgger/ui2/templates/index.html`
as base for your customization.
Flasgger supports Swagger UI versions 2 and 3, The version 3 is still experimental but you
can try setting `app.config['SWAGGER']['uiversion']`.
```python
app = Flask(__name__)
app.config['SWAGGER'] = {
'title': 'My API',
'uiversion': 3
}
swagger = Swagger(app)
```
# OpenAPI 3.0 Support
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'`.
For an example of this that uses `callbacks` and `requestBody`, see the [callbacks example](examples/callbacks.py).
## Externally loading Swagger UI and jQuery JS/CSS
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.
The following example loads Swagger UI and jQuery versions from unpkg.com:
```
swagger_config = Swagger.DEFAULT_CONFIG
swagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js'
swagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js'
swagger_config['jquery_js'] = '//unpkg.com/jquery@2.2.4/dist/jquery.min.js'
swagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css'
Swagger(app, config=swagger_config)
```
# Initializing Flasgger with default data.
You can start your Swagger spec with any default data providing a template:
```python
template = {
"swagger": "2.0",
"info": {
"title": "My API",
"description": "API for my data",
"contact": {
"responsibleOrganization": "ME",
"responsibleDeveloper": "Me",
"email": "me@me.com",
"url": "www.me.com",
},
"termsOfService": "http://me.com/terms",
"version": "0.0.1"
},
"host": "mysite.com", # overrides localhost:500
"basePath": "/api", # base bash for blueprint registration
"schemes": [
"http",
"https"
],
"operationId": "getmyData"
}
swagger = Swagger(app, template=template)
```
And then the template is the default data unless some view changes it. You
can also provide all your specs as template and have no views. Or views in
external APP.
## Getting default data at runtime
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`.
```py
from flask import Flask
from flasgger import, Swagger, LazyString, LazyJSONEncoder
app = Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)
app.json_encoder = LazyJSONEncoder
template = dict(
info={
'title': LazyString(lambda: 'Lazy Title'),
'version': LazyString(lambda: '99.9.9'),
'description': LazyString(lambda: 'Hello Lazy World'),
'termsOfService': LazyString(lambda: '/there_is_no_tos')
},
host=LazyString(lambda: request.host),
schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')],
foo=LazyString(lambda: "Bar")
)
Swagger(app, template=template)
```
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.
## Behind a reverse proxy
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/),
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:
```python
from flask import Flask, request
from flasgger import Swagger, LazyString, LazyJSONEncoder
app = Flask(__name__)
app.json_encoder = LazyJSONEncoder
template = dict(swaggerUiPrefix=LazyString(lambda : request.environ.get('HTTP_X_SCRIPT_NAME', '')))
swagger = Swagger(app, template=template)
```
# Customize default configurations
Custom configurations such as a different specs route or disabling Swagger UI can be provided to Flasgger:
```python
swagger_config = {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_url_path": "/flasgger_static",
# "static_folder": "static", # must be set by user
"swagger_ui": True,
"specs_route": "/apidocs/"
}
swagger = Swagger(app, config=swagger_config)
```
## Extracting Definitions
Definitions can be extracted when `id` is found in spec, example:
```python
from flask import Flask, jsonify
from flasgger import Swagger
app = Flask(__name__)
swagger = Swagger(app)
@app.route('/colors/<palette>/')
def colors(palette):
"""Example endpoint returning a list of colors by palette
---
parameters:
- name: palette
in: path
type: string
enum: ['all', 'rgb', 'cmyk']
required: true
default: all
responses:
200:
description: A list of colors (may be filtered by palette)
schema:
id: Palette
type: object
properties:
palette_name:
type: array
items:
schema:
id: Color
type: string
examples:
rgb: ['red', 'green', 'blue']
"""
all_colors = {
'cmyk': ['cyan', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
if palette == 'all':
result = all_colors
else:
result = {palette: all_colors.get(palette)}
return jsonify(result)
app.run(debug=True)
```
In this example you do not have to pass `definitions` but need to add `id` to
your schemas.
## Python2 Compatibility
Version `0.9.5.*` will be the last verison that supports Python2.
Please direct discussions to [#399](https://github.com/flasgger/flasgger/issues/399).
Raw data
{
"_id": null,
"home_page": "https://github.com/flasgger/flasgger/",
"name": "flasgger",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Bruno Rocha, Zixuan Rao, Flasgger team",
"author_email": "flasgger@flasgger.org",
"download_url": "https://files.pythonhosted.org/packages/8a/e4/05e80adeadc39f171b51bd29b24a6d9838127f3aaa1b07c1501e662a8cee/flasgger-0.9.7.1.tar.gz",
"platform": "any",
"description": "# Flasgger\n## Easy Swagger UI for your Flask API\n\n[](https://travis-ci.com/flasgger/flasgger)\n[](https://landscape.io/github/rochacbruno/flasgger/master)\n[](https://coveralls.io/github/rochacbruno/flasgger?branch=master)\n[](https://pypi.python.org/pypi/flasgger)\n <a target=\"_blank\" href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=rochacbruno%40gmail%2ecom&lc=BR&item_name=Flasgger&no_note=0&currency_code=USD&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>\n\n\n\n\nFlasgger 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.\n\nFlasgger 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.\n\nFlasgger 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**.\n\nFlasgger 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.\n\nFlasgger is compatible with `Flask-RESTful` so you can use `Resources` and `swag` specifications together, take a look at [restful example.](examples/restful.py)\n\nFlasgger 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)\n\nTable of Contents\n=================\n\n* [Top Contributors](#top-contributors)\n* [Examples and demo app](#examples-and-demo-app)\n * [Docker](#docker)\n* [Installation](#installation)\n* [Getting started](#getting-started)\n * [Using docstrings as specification](#using-docstrings-as-specification)\n * [Using external YAML files](#using-external-yaml-files)\n * [Using dictionaries as raw specs](#using-dictionaries-as-raw-specs)\n * [Using Marshmallow Schemas](#using-marshmallow-schemas)\n * [Using <strong>Flask RESTful</strong> Resources](#using-flask-restful-resources)\n * [Auto-parsing external YAML docs and MethodViews](#auto-parsing-external-yaml-docs-and-methodviews)\n * [Handling multiple http methods and routes for a single function](#handling-multiple-http-methods-and-routes-for-a-single-function)\n* [Use the same data to validate your API POST body.](#use-the-same-data-to-validate-your-api-post-body)\n * [Custom validation](#custom-validation)\n * [Validation Error handling](#validation-error-handling)\n* [Get defined schemas as python dictionaries](#get-defined-schemas-as-python-dictionaries)\n* [HTML sanitizer](#html-sanitizer)\n* [Swagger UI and templates](#swagger-ui-and-templates)\n* [OpenAPI 3.0 Support](#openapi-30-support)\n * [Externally loading Swagger UI and jQuery JS/CSS](#externally-loading-swagger-ui-and-jquery-jscss)\n* [Initializing Flasgger with default data.](#initializing-flasgger-with-default-data)\n * [Getting default data at runtime](#getting-default-data-at-runtime)\n * [Behind a reverse proxy](#behind-a-reverse-proxy)\n* [Customize default configurations](#customize-default-configurations)\n * [Extracting Definitions](#extracting-definitions)\n * [Python2 Compatibility](#python2-compatibility)\n\nCreated by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)\n\n# Top Contributors\n\n[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/0)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/1)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/2)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/3)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/4)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/5)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/6)[](https://sourcerer.io/fame/rochacbruno/rochacbruno/flasgger/links/7)\n\n# Examples and demo app\n\nThere are some [example applications](examples/) and you can also play with examples in [Flasgger demo app](http://flasgger.pythonanywhere.com/)\n\n> NOTE: all the examples apps are also test cases and run automatically in Travis CI to ensure quality and coverage.\n\n## Docker\n\nThe examples and demo app can also be built and run as a Docker image/container:\n\n```\ndocker build -t flasgger .\ndocker run -it --rm -p 5000:5000 --name flasgger flasgger\n```\nThen access the Flasgger demo app at http://localhost:5000 .\n\n# Installation\n\n> under your virtualenv do:\n\nEnsure you have latest setuptools\n```\npip install -U setuptools\n```\n\nthen install beta version (recommended)\n\n```\npip install flasgger==0.9.7b2\n```\n\nor (latest stable for legacy apps)\n\n```\npip install flasgger==0.9.5\n```\n\nor (dev version)\n\n```\npip install https://github.com/flasgger/flasgger/tarball/master\n```\n\n> NOTE: If you want to use **Marshmallow Schemas** you also need to run `pip install marshmallow apispec`\n\n## How to run tests\n\n(You may see the command in [.travis.yml](./.travis.yml) for `before_install` part)\n\nIn your virtualenv:\n\n```\npip install -r requirements.txt\npip install -r requirements-dev.txt\nmake test\n```\n\n# Getting started\n\n## Using docstrings as specification\n\nCreate a file called for example `colors.py`\n\n```python\nfrom flask import Flask, jsonify\nfrom flasgger import Swagger\n\napp = Flask(__name__)\nswagger = Swagger(app)\n\n@app.route('/colors/<palette>/')\ndef colors(palette):\n \"\"\"Example endpoint returning a list of colors by palette\n This is using docstrings for specifications.\n ---\n parameters:\n - name: palette\n in: path\n type: string\n enum: ['all', 'rgb', 'cmyk']\n required: true\n default: all\n definitions:\n Palette:\n type: object\n properties:\n palette_name:\n type: array\n items:\n $ref: '#/definitions/Color'\n Color:\n type: string\n responses:\n 200:\n description: A list of colors (may be filtered by palette)\n schema:\n $ref: '#/definitions/Palette'\n examples:\n rgb: ['red', 'green', 'blue']\n \"\"\"\n all_colors = {\n 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],\n 'rgb': ['red', 'green', 'blue']\n }\n if palette == 'all':\n result = all_colors\n else:\n result = {palette: all_colors.get(palette)}\n\n return jsonify(result)\n\napp.run(debug=True)\n```\n\nNow run:\n\n```\npython colors.py\n```\n\nAnd go to: [http://localhost:5000/apidocs/](http://localhost:5000/apidocs/)\n\nYou should get:\n\n\n\n## Using external YAML files\n\nSave a new file `colors.yml`\n\n```yaml\nExample endpoint returning a list of colors by palette\nIn this example the specification is taken from external YAML file\n---\nparameters:\n - name: palette\n in: path\n type: string\n enum: ['all', 'rgb', 'cmyk']\n required: true\n default: all\ndefinitions:\n Palette:\n type: object\n properties:\n palette_name:\n type: array\n items:\n $ref: '#/definitions/Color'\n Color:\n type: string\nresponses:\n 200:\n description: A list of colors (may be filtered by palette)\n schema:\n $ref: '#/definitions/Palette'\n examples:\n rgb: ['red', 'green', 'blue']\n```\n\n\nlets use the same example changing only the view function.\n\n```python\nfrom flasgger import swag_from\n\n@app.route('/colors/<palette>/')\n@swag_from('colors.yml')\ndef colors(palette):\n ...\n```\n\nIf you do not want to use the decorator you can use the docstring `file:` shortcut.\n\n```python\n@app.route('/colors/<palette>/')\ndef colors(palette):\n \"\"\"\n file: colors.yml\n \"\"\"\n ...\n```\n\n\n## Using dictionaries as raw specs\n\nCreate a Python dictionary as:\n\n```python\nspecs_dict = {\n \"parameters\": [\n {\n \"name\": \"palette\",\n \"in\": \"path\",\n \"type\": \"string\",\n \"enum\": [\n \"all\",\n \"rgb\",\n \"cmyk\"\n ],\n \"required\": \"true\",\n \"default\": \"all\"\n }\n ],\n \"definitions\": {\n \"Palette\": {\n \"type\": \"object\",\n \"properties\": {\n \"palette_name\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/definitions/Color\"\n }\n }\n }\n },\n \"Color\": {\n \"type\": \"string\"\n }\n },\n \"responses\": {\n \"200\": {\n \"description\": \"A list of colors (may be filtered by palette)\",\n \"schema\": {\n \"$ref\": \"#/definitions/Palette\"\n },\n \"examples\": {\n \"rgb\": [\n \"red\",\n \"green\",\n \"blue\"\n ]\n }\n }\n }\n}\n```\n\nNow take the same function and use the dict in the place of YAML file.\n\n```python\n@app.route('/colors/<palette>/')\n@swag_from(specs_dict)\ndef colors(palette):\n \"\"\"Example endpoint returning a list of colors by palette\n In this example the specification is taken from specs_dict\n \"\"\"\n ...\n```\n\n## Using Marshmallow Schemas\n\n> FIRST: `pip install marshmallow apispec`\n\n> USAGE #1: `SwaggerView`\n\n```python\nfrom flask import Flask, jsonify\nfrom flasgger import Swagger, SwaggerView, Schema, fields\n\n\nclass Color(Schema):\n name = fields.Str()\n\nclass Palette(Schema):\n pallete_name = fields.Str()\n colors = fields.Nested(Color, many=True)\n\nclass PaletteView(SwaggerView):\n parameters = [\n {\n \"name\": \"palette\",\n \"in\": \"path\",\n \"type\": \"string\",\n \"enum\": [\"all\", \"rgb\", \"cmyk\"],\n \"required\": True,\n \"default\": \"all\"\n }\n ]\n responses = {\n 200: {\n \"description\": \"A list of colors (may be filtered by palette)\",\n \"schema\": Palette\n }\n }\n\n def get(self, palette):\n \"\"\"\n Colors API using schema\n This example is using marshmallow schemas\n \"\"\"\n all_colors = {\n 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],\n 'rgb': ['red', 'green', 'blue']\n }\n if palette == 'all':\n result = all_colors\n else:\n result = {palette: all_colors.get(palette)}\n return jsonify(result)\n\napp = Flask(__name__)\nswagger = Swagger(app)\n\napp.add_url_rule(\n '/colors/<palette>',\n view_func=PaletteView.as_view('colors'),\n methods=['GET']\n)\n\napp.run(debug=True)\n\n```\n\n> USAGE #2: `Custom Schema from flasgger`\n\n- `Body` - support all fields in marshmallow\n- `Query` - support simple fields in marshmallow (Int, String and etc)\n- `Path` - support only int and str\n\n```python\nfrom flask import Flask, abort\nfrom flasgger import Swagger, Schema, fields\nfrom marshmallow.validate import Length, OneOf\n\napp = Flask(__name__)\nSwagger(app)\n\nswag = {\"swag\": True,\n \"tags\": [\"demo\"],\n \"responses\": {200: {\"description\": \"Success request\"},\n 400: {\"description\": \"Validation error\"}}}\n\n\nclass Body(Schema):\n color = fields.List(fields.String(), required=True, validate=Length(max=5), example=[\"white\", \"blue\", \"red\"])\n\n def swag_validation_function(self, data, main_def):\n self.load(data)\n\n def swag_validation_error_handler(self, err, data, main_def):\n abort(400, err)\n\n\nclass Query(Schema):\n color = fields.String(required=True, validate=OneOf([\"white\", \"blue\", \"red\"]))\n\n def swag_validation_function(self, data, main_def):\n self.load(data)\n\n def swag_validation_error_handler(self, err, data, main_def):\n abort(400, err)\n\n swag_in = \"query\"\n\n\n@app.route(\"/color/<id>/<name>\", methods=[\"POST\"], **swag)\ndef index(body: Body, query: Query, id: int, name: str):\n return {\"body\": body, \"query\": query, \"id\": id, \"name\": name}\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n```\n\n\n> NOTE: take a look at `examples/validation.py` for a more complete example.\n\n\n> NOTE: when catching arguments in path rule always use explicit types, bad: ``/api/<username>`` good: ``/api/<string:username>``\n\n\n## Using **Flask RESTful** Resources\n\nFlasgger is compatible with Flask-RESTful you only need to install `pip install flask-restful` and then:\n\n```python\nfrom flask import Flask\nfrom flasgger import Swagger\nfrom flask_restful import Api, Resource\n\napp = Flask(__name__)\napi = Api(app)\nswagger = Swagger(app)\n\nclass Username(Resource):\n def get(self, username):\n \"\"\"\n This examples uses FlaskRESTful Resource\n It works also with swag_from, schemas and spec_dict\n ---\n parameters:\n - in: path\n name: username\n type: string\n required: true\n responses:\n 200:\n description: A single user item\n schema:\n id: User\n properties:\n username:\n type: string\n description: The name of the user\n default: Steven Wilson\n \"\"\"\n return {'username': username}, 200\n\n\napi.add_resource(Username, '/username/<username>')\n\napp.run(debug=True)\n```\n\n## Auto-parsing external YAML docs and `MethodView`s\n\nFlasgger 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`.\n\nAdditionally, 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`.\n\n## Handling multiple http methods and routes for a single function\n\nYou can separate specifications by endpoint or methods\n\n```python\nfrom flasgger.utils import swag_from\n\n@app.route('/api/<string:username>', endpoint='with_user_name', methods=['PUT', 'GET'])\n@app.route('/api/', endpoint='without_user_name')\n@swag_from('path/to/external_file.yml', endpoint='with_user_name')\n@swag_from('path/to/external_file_no_user_get.yml', endpoint='without_user_name', methods=['GET'])\n@swag_from('path/to/external_file_no_user_put.yml', endpoint='without_user_name', methods=['PUT'])\ndef fromfile_decorated(username=None):\n if not username:\n return \"No user!\"\n return jsonify({'username': username})\n```\n\nAnd the same can be achieved with multiple methods in a `MethodView` or `SwaggerView` by\nregistering the `url_rule` many times. Take a look at `examples/example_app`\n\n\n# Use the same data to validate your API POST body.\n\nSetting `swag_from`'s _validation_ parameter to `True` will validate incoming data automatically:\n\n```python\nfrom flasgger import swag_from\n\n@swag_from('defs.yml', validation=True)\ndef post():\n # if not validate returns ValidationError response with status 400\n # also returns the validation message.\n```\n\nUsing `swagger.validate` annotation is also possible:\n\n```python\nfrom flasgger import Swagger\n\nswagger = Swagger(app)\n\n@swagger.validate('UserSchema')\ndef post():\n '''\n file: defs.yml\n '''\n # if not validate returns ValidationError response with status 400\n # also returns the validation message.\n```\n\nYet you can call `validate` manually:\n\n```python\nfrom flasgger import swag_from, validate\n\n@swag_from('defs.yml')\ndef post():\n validate(request.json, 'UserSchema', 'defs.yml')\n # if not validate returns ValidationError response with status 400\n # also returns the validation message.\n```\n\nIt is also possible to define `validation=True` in `SwaggerView` and also use\n`specs_dict` for validation.\n\nTake a look at `examples/validation.py` for more information.\n\nAll validation options can be found at http://json-schema.org/latest/json-schema-validation.html\n\n### Custom validation\n\nBy default Flasgger will use [python-jsonschema](https://python-jsonschema.readthedocs.io/en/latest/)\nto perform validation.\n\nCustom validation functions are supported as long as they meet the requirements:\n - take two, and only two, positional arguments:\n - the data to be validated as the first; and\n - the schema to validate against as the second argument\n - raise any kind of exception when validation fails.\n\nAny return value is discarded.\n\n\nProviding the function to the Swagger instance will make it the default:\n\n```python\nfrom flasgger import Swagger\n\nswagger = Swagger(app, validation_function=my_validation_function)\n```\n\nProviding the function as parameter of `swag_from` or `swagger.validate`\nannotations or directly to the `validate` function will force it's use\nover the default validation function for Swagger:\n\n```python\nfrom flasgger import swag_from\n\n@swag_from('spec.yml', validation=True, validation_function=my_function)\n...\n```\n\n```python\nfrom flasgger import Swagger\n\nswagger = Swagger(app)\n\n@swagger.validate('Pet', validation_function=my_function)\n...\n```\n\n```python\nfrom flasgger import validate\n\n...\n\n validate(\n request.json, 'Pet', 'defs.yml', validation_function=my_function)\n```\n\n### Validation Error handling\n\nBy default Flasgger will handle validation errors by aborting the\nrequest with a 400 BAD REQUEST response with the error message.\n\nA custom validation error handling function can be provided to\nsupersede default behavior as long as it meets the requirements:\n - take three, and only three, positional arguments:\n - the error raised as the first;\n - the data which failed validation as the second; and\n - the schema used in to validate as the third argument\n\n\nProviding the function to the Swagger instance will make it the default:\n\n```python\nfrom flasgger import Swagger\n\nswagger = Swagger(app, validation_error_handler=my_handler)\n```\n\nProviding the function as parameter of `swag_from` or `swagger.validate`\nannotations or directly to the `validate` function will force it's use\nover the default validation function for Swagger:\n\n```python\nfrom flasgger import swag_from\n\n@swag_from(\n 'spec.yml', validation=True, validation_error_handler=my_handler)\n...\n```\n\n```python\nfrom flasgger import Swagger\n\nswagger = Swagger(app)\n\n@swagger.validate('Pet', validation_error_handler=my_handler)\n...\n```\n\n```python\nfrom flasgger import validate\n\n...\n\n validate(\n request.json, 'Pet', 'defs.yml',\n validation_error_handler=my_handler)\n```\n\nExamples of use of a custom validation error handler function can be\nfound at [example validation_error_handler.py](examples/validation_error_handler.py)\n\n# Get defined schemas as python dictionaries\n\nYou may wish to use schemas you defined in your Swagger specs as dictionaries\nwithout replicating the specification. For that you can use the `get_schema`\nmethod:\n\n```python\nfrom flask import Flask, jsonify\nfrom flasgger import Swagger, swag_from\n\napp = Flask(__name__)\nswagger = Swagger(app)\n\n@swagger.validate('Product')\ndef post():\n \"\"\"\n post endpoint\n ---\n tags:\n - products\n parameters:\n - name: body\n in: body\n required: true\n schema:\n id: Product\n required:\n - name\n properties:\n name:\n type: string\n description: The product's name.\n default: \"Guarana\"\n responses:\n 200:\n description: The product inserted in the database\n schema:\n $ref: '#/definitions/Product'\n \"\"\"\n rv = db.insert(request.json)\n return jsonify(rv)\n\n...\n\nproduct_schema = swagger.get_schema('product')\n```\n\nThis method returns a dictionary which contains the Flasgger schema id,\nall defined parameters and a list of required parameters.\n\n# HTML sanitizer\n\nBy default Flasgger will try to sanitize the content in YAML definitions\nreplacing every ```\\n``` with ```<br>``` but you can change this behaviour\nsetting another kind of sanitizer.\n\n```python\nfrom flasgger import Swagger, NO_SANITIZER\n\napp =Flask()\nswagger = Swagger(app, sanitizer=NO_SANITIZER)\n```\n\nYou can write your own sanitizer\n\n```python\nswagger = Swagger(app, sanitizer=lambda text: do_anything_with(text))\n```\n\nThere is also a Markdown parser available, if you want to be able to render\nMarkdown in your specs description use **MK_SANITIZER**\n\n\n# Swagger UI and templates\n\nYou can override the `templates/flasgger/index.html` in your application and\nthis template will be the `index.html` for SwaggerUI. Use `flasgger/ui2/templates/index.html`\nas base for your customization.\n\nFlasgger supports Swagger UI versions 2 and 3, The version 3 is still experimental but you\ncan try setting `app.config['SWAGGER']['uiversion']`.\n\n```python\napp = Flask(__name__)\napp.config['SWAGGER'] = {\n 'title': 'My API',\n 'uiversion': 3\n}\nswagger = Swagger(app)\n\n```\n\n# OpenAPI 3.0 Support\n\nThere 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'`.\n\nFor an example of this that uses `callbacks` and `requestBody`, see the [callbacks example](examples/callbacks.py).\n\n## Externally loading Swagger UI and jQuery JS/CSS\n\nStarting 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.\n\nThe following example loads Swagger UI and jQuery versions from unpkg.com:\n\n```\nswagger_config = Swagger.DEFAULT_CONFIG\nswagger_config['swagger_ui_bundle_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js'\nswagger_config['swagger_ui_standalone_preset_js'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js'\nswagger_config['jquery_js'] = '//unpkg.com/jquery@2.2.4/dist/jquery.min.js'\nswagger_config['swagger_ui_css'] = '//unpkg.com/swagger-ui-dist@3/swagger-ui.css'\nSwagger(app, config=swagger_config)\n```\n\n# Initializing Flasgger with default data.\n\nYou can start your Swagger spec with any default data providing a template:\n\n```python\ntemplate = {\n \"swagger\": \"2.0\",\n \"info\": {\n \"title\": \"My API\",\n \"description\": \"API for my data\",\n \"contact\": {\n \"responsibleOrganization\": \"ME\",\n \"responsibleDeveloper\": \"Me\",\n \"email\": \"me@me.com\",\n \"url\": \"www.me.com\",\n },\n \"termsOfService\": \"http://me.com/terms\",\n \"version\": \"0.0.1\"\n },\n \"host\": \"mysite.com\", # overrides localhost:500\n \"basePath\": \"/api\", # base bash for blueprint registration\n \"schemes\": [\n \"http\",\n \"https\"\n ],\n \"operationId\": \"getmyData\"\n}\n\nswagger = Swagger(app, template=template)\n\n```\n\nAnd then the template is the default data unless some view changes it. You\ncan also provide all your specs as template and have no views. Or views in\nexternal APP.\n\n## Getting default data at runtime\n\nSometimes 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`.\n\n```py\nfrom flask import Flask\nfrom flasgger import, Swagger, LazyString, LazyJSONEncoder\n\napp = Flask(__init__)\n\n# Set the custom Encoder (Inherit it if you need to customize)\napp.json_encoder = LazyJSONEncoder\n\n\ntemplate = dict(\n info={\n 'title': LazyString(lambda: 'Lazy Title'),\n 'version': LazyString(lambda: '99.9.9'),\n 'description': LazyString(lambda: 'Hello Lazy World'),\n 'termsOfService': LazyString(lambda: '/there_is_no_tos')\n },\n host=LazyString(lambda: request.host),\n schemes=[LazyString(lambda: 'https' if request.is_secure else 'http')],\n foo=LazyString(lambda: \"Bar\")\n)\nSwagger(app, template=template)\n\n```\n\nThe `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.\n\n## Behind a reverse proxy\n\nSometimes you're serving your swagger docs behind an reverse proxy (e.g. NGINX). When following the [Flask guidance](http://flask.pocoo.org/snippets/35/),\nthe swagger docs will load correctly, but the \"Try it Out\" button points to the wrong place. This can be fixed with the following code:\n\n```python\nfrom flask import Flask, request\nfrom flasgger import Swagger, LazyString, LazyJSONEncoder\n\napp = Flask(__name__)\napp.json_encoder = LazyJSONEncoder\n\ntemplate = dict(swaggerUiPrefix=LazyString(lambda : request.environ.get('HTTP_X_SCRIPT_NAME', '')))\nswagger = Swagger(app, template=template)\n\n```\n\n# Customize default configurations\n\nCustom configurations such as a different specs route or disabling Swagger UI can be provided to Flasgger:\n\n```python\nswagger_config = {\n \"headers\": [\n ],\n \"specs\": [\n {\n \"endpoint\": 'apispec_1',\n \"route\": '/apispec_1.json',\n \"rule_filter\": lambda rule: True, # all in\n \"model_filter\": lambda tag: True, # all in\n }\n ],\n \"static_url_path\": \"/flasgger_static\",\n # \"static_folder\": \"static\", # must be set by user\n \"swagger_ui\": True,\n \"specs_route\": \"/apidocs/\"\n}\n\nswagger = Swagger(app, config=swagger_config)\n\n```\n\n## Extracting Definitions\n\nDefinitions can be extracted when `id` is found in spec, example:\n\n```python\nfrom flask import Flask, jsonify\nfrom flasgger import Swagger\n\napp = Flask(__name__)\nswagger = Swagger(app)\n\n@app.route('/colors/<palette>/')\ndef colors(palette):\n \"\"\"Example endpoint returning a list of colors by palette\n ---\n parameters:\n - name: palette\n in: path\n type: string\n enum: ['all', 'rgb', 'cmyk']\n required: true\n default: all\n responses:\n 200:\n description: A list of colors (may be filtered by palette)\n schema:\n id: Palette\n type: object\n properties:\n palette_name:\n type: array\n items:\n schema:\n id: Color\n type: string\n examples:\n rgb: ['red', 'green', 'blue']\n \"\"\"\n all_colors = {\n 'cmyk': ['cyan', 'magenta', 'yellow', 'black'],\n 'rgb': ['red', 'green', 'blue']\n }\n if palette == 'all':\n result = all_colors\n else:\n result = {palette: all_colors.get(palette)}\n\n return jsonify(result)\n\napp.run(debug=True)\n```\n\nIn this example you do not have to pass `definitions` but need to add `id` to\nyour schemas.\n\n## Python2 Compatibility\n\nVersion `0.9.5.*` will be the last verison that supports Python2.\nPlease direct discussions to [#399](https://github.com/flasgger/flasgger/issues/399).\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Extract swagger specs from your flask project",
"version": "0.9.7.1",
"project_urls": {
"Homepage": "https://github.com/flasgger/flasgger/"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "8ae405e80adeadc39f171b51bd29b24a6d9838127f3aaa1b07c1501e662a8cee",
"md5": "3f2d4b14b25b22a0e99008c6ad826ba4",
"sha256": "ca098e10bfbb12f047acc6299cc70a33851943a746e550d86e65e60d4df245fb"
},
"downloads": -1,
"filename": "flasgger-0.9.7.1.tar.gz",
"has_sig": false,
"md5_digest": "3f2d4b14b25b22a0e99008c6ad826ba4",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 3979409,
"upload_time": "2023-05-18T17:15:21",
"upload_time_iso_8601": "2023-05-18T17:15:21.328461Z",
"url": "https://files.pythonhosted.org/packages/8a/e4/05e80adeadc39f171b51bd29b24a6d9838127f3aaa1b07c1501e662a8cee/flasgger-0.9.7.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-05-18 17:15:21",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "flasgger",
"github_project": "flasgger",
"travis_ci": true,
"coveralls": true,
"github_actions": false,
"requirements": [],
"tox": true,
"lcname": "flasgger"
}