Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Flasgger

Easy Swagger UI for your Flask API

Build StatusCode HealthCoverage StatusPyPIDonate with Paypal

flasgger

Flasgger is a Flask extension to extract OpenAPI-Specification from all Flask views registered in your API.

Flasgger also comes with SwaggerUI embedded so you can access http://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.

Flasgger also supports Marshmallow APISpec as base template for specification, if you are using APISPec from Marshmallow take a look at apispec example.

Top Contributors

Examples and demo app

There are some example applications and you can also play with examples in Flasgger demo app

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

pip install flasgger

or (dev version)

pip install https://github.com/rochacbruno/flasgger/tarball/master

NOTE: If you want to use Marshmallow Schemas you also need to run pip install marshmallow apispec

Getting started

Using docstrings as specification

Create a file called for example colors.py

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

Now run:

python colors.py

And go to: http://localhost:5000/apidocs/

You should get:

colors

Using external YAML files

Save a new file colors.yml

Example endpoint returning a list of colors by paletteIn this example the specification is taken from external YAML file
---
parameters:
- name: palettein: pathtype: stringenum: ['all', 'rgb', 'cmyk']required: truedefault: alldefinitions:
Palette:
type: objectproperties:
palette_name:
type: arrayitems:
$ref: '#/definitions/Color'Color:
type: stringresponses:
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.

fromflasggerimportswag_from@app.route('/colors/<palette>/')@swag_from('colors.yml')defcolors(palette):
...

If you do not want to use the decorator you can use the docstring file: shortcut.

@app.route('/colors/<palette>/')defcolors(palette):
""" file: colors.yml """
...

Using dictionaries as raw specs

Create a Python dictionary as:

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.

@app.route('/colors/<palette>/')@swag_from(specs_dict)defcolors(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

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, SwaggerView, Schema, fieldsclassColor(Schema):
name=fields.Str()
classPalette(Schema):
pallete_name=fields.Str()
colors=fields.Nested(Color, many=True)
classPaletteView(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
}
}
defget(self, palette):
""" Colors API using schema This example is using marshmallow schemas """all_colors= {
'cmyk': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(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
fromflaskimportFlask, abortfromflasggerimportSwagger, Schema, fieldsfrommarshmallow.validateimportLength, OneOfapp=Flask(__name__)
Swagger(app)
swag= {"swag": True,
"tags": ["demo"],
"responses": {200: {"description": "Success request"},
400: {"description": "Validation error"}}}
classBody(Schema):
color=fields.List(fields.String(), required=True, validate=Length(max=5), example=["white", "blue", "red"])
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
classQuery(Schema):
color=fields.String(required=True, validate=OneOf(["white", "blue", "red"]))
defswag_validation_function(self, data, main_def):
self.load(data)
defswag_validation_error_handler(self, err, data, main_def):
abort(400, err)
swag_in="query"@app.route("/color/<id>/<name>", methods=["POST"], **swag)defindex(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:

fromflaskimportFlaskfromflasggerimportSwaggerfromflask_restfulimportApi, Resourceapp=Flask(__name__)
api=Api(app)
swagger=Swagger(app)
classUsername(Resource):
defget(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}, 200api.add_resource(Username, '/username/<username>')
app.run(debug=True)

Auto-parsing external YAML docs and MethodViews

Flasgger can be configured to auto-parse external YAML API docs. Set a doc_dir 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 MethodViews 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

fromflasgger.utilsimportswag_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'])deffromfile_decorated(username=None):
ifnotusername:
return"No user!"returnjsonify({'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:

fromflasggerimportswag_from@swag_from('defs.yml', validation=True)defpost():
# if not validate returns ValidationError response with status 400# also returns the validation message.

Using swagger.validate annotation is also possible:

fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('UserSchema')defpost():
''' file: defs.yml '''# if not validate returns ValidationError response with status 400# also returns the validation message.

Yet you can call validate manually:

fromflasggerimportswag_from, validate@swag_from('defs.yml')defpost():
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 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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_function=my_function)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_function=my_function)
...
fromflasggerimportvalidate
...
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:

fromflasggerimportSwaggerswagger=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:

fromflasggerimportswag_from@swag_from('spec.yml', validation=True, validation_error_handler=my_handler)
...
fromflasggerimportSwaggerswagger=Swagger(app)
@swagger.validate('Pet', validation_error_handler=my_handler)
...
fromflasggerimportvalidate
...
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

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:

fromflaskimportFlask, jsonifyfromflasggerimportSwagger, swag_fromapp=Flask(__name__)
swagger=Swagger(app)
@swagger.validate('Product')defpost():
""" 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)
returnjsonify(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.

fromflasggerimportSwagger, NO_SANITIZERapp=Flask()
swagger=Swagger(app, sanitizer=NO_SANITIZER)

You can write your own sanitizer

swagger=Swagger(app, sanitizer=lambdatext: 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'].

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.

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:

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.

fromflaskimportFlaskfromflasggerimport, Swagger, LazyString, LazyJSONEncoderapp=Flask(__init__)
# Set the custom Encoder (Inherit it if you need to customize)app.json_encoder=LazyJSONEncodertemplate=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'ifrequest.is_secureelse'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, 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:

fromflaskimportFlask, requestfromflasggerimportSwagger, LazyString, LazyJSONEncoderapp=Flask(__name__)
app.json_encoder=LazyJSONEncodertemplate=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:

swagger_config= {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_1',
"route": '/apispec_1.json',
"rule_filter": lambdarule: True, # all in"model_filter": lambdatag: 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:

fromflaskimportFlask, jsonifyfromflasggerimportSwaggerapp=Flask(__name__)
swagger=Swagger(app)
@app.route('/colors/<palette>/')defcolors(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': ['cian', 'magenta', 'yellow', 'black'],
'rgb': ['red', 'green', 'blue']
}
ifpalette=='all':
result=all_colorselse:
result= {palette: all_colors.get(palette)}
returnjsonify(result)
app.run(debug=True)

In this example you do not have to pass definitions but need to add id to your schemas.

About

Easy OpenAPI specs and Swagger UI for your Flask API

Resources

Code of conduct

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages