flask_swag package

Submodules

flask_swag.core module

core

Core API for swagger.

flask_swag.core.Contact(**kwargs)

Contact info

flask_swag.core.ExternalDocumentation(**kwargs)

Description of external documentation

flask_swag.core.Header(**kwargs)

Header info

flask_swag.core.Info(**kwargs)

Swagger metadata

flask_swag.core.Items(**kwargs)

Description of items

flask_swag.core.License(**kwargs)

License info

flask_swag.core.Operation(**kwargs)

Operations for each method in PathItem

flask_swag.core.Parameter(**kwargs)

Parameter info

flask_swag.core.PathItem(**kwargs)

Items for each path

flask_swag.core.Response(**kwargs)

Description of responses of operation

flask_swag.core.Schema(**kwargs)

Basic schema info

flask_swag.core.Swagger(**kwargs)

Swagger root object

flask_swag.core.dump(swagger, schema=<SwaggerSchema(many=False, strict=False)>)[source]

Dump swagger dict to swagger JSON spec

flask_swag.core.make_dict_factory(schema)[source]
flask_swag.core.parameters_from_object_schema(schema, in_='formData')[source]

Convert object schema to parameters.

flask_swag.ext module

ext

Utilities for optional external libraries.

flask_swag.ext.dump_formencode(formencode_schema)[source]

Dump formencode schema to json schema using [forencode_jsonschema]( https://github.com/Hardtack/formencode_jsonschema)

flask_swag.ext.dump_marshmallow(marshmallow_schema)[source]

Dump marshmallow schema to json schema using [marshmallow-jsonschema]( https://github.com/fuhrysteve/marshmallow-jsonschema)

flask_swag.fields module

fields

Definitions of custom fields for marshmallow schema.

class flask_swag.fields.TypedDict(key_field, nested_field, *args, **kwargs)[source]

Bases: marshmallow.fields.Field

Typed dict field.

flask_swag.globals module

globals

Global variables.

flask_swag.globals.RESOURCES_DIR = '/home/docs/checkouts/readthedocs.org/user_builds/flask-swag/checkouts/latest/flask_swag/resources'

Resources root directory

flask_swag.globals.ROOT_DIR = '/home/docs/checkouts/readthedocs.org/user_builds/flask-swag/checkouts/latest/flask_swag'

Package root directory

flask_swag.globals.SWAGGER_UI_DIR = '/home/docs/checkouts/readthedocs.org/user_builds/flask-swag/checkouts/latest/flask_swag/resources/swagger-ui'

Root directory of swagger-ui

flask_swag.mark module

mark

Mark flask view with swagger spec.

class flask_swag.mark.Mark[source]

Bases: object

Utility that marks flask view with swagger spec.

You can add fields to view’s operation object using this class.

mark = Mark()

@app.route('/users/')
@mark({
    'summary': "List users.",
    'produces': ['application/json'],
})
def index():
    return jsonify(get_users())

The mark will be saved to _swag property of view function. So the @mark decorator should be located right under the @app.route.

You can also use convinience methods like responses(), summary(), ...

@app.route('/users/', methods=['POST'])
@mark.summary("Create a new user")
def create():
    pass

You can remove some field from spec by using unmark()

@app.route('/users/<int:user_id')
@mark.unmark('description')
@mark({
    'summary': "Read a user",
    'description': "Wooah"
})
def read(user_id):
    pass
description(description: str)[source]

Mark description to view.

description_from_docstring(fn)[source]

Mark description from docstring,

form(name, python_type, optional=False, **kwargs)[source]

Mark simple form parameter.

formencode(formencode_schema, in_='formData')[source]

Mark formencode schema as parameter.

get_swag(fn)[source]
marshmallow(formencode_schema, in_='formData')[source]

Mark marshmallow schema as parameter.

merge_swag(fn, swag)[source]
parameter(parameter)[source]

Mark parameter to view

query(name, python_type, optional=False, **kwargs)[source]

Mark simple query parameter.

response(status, response_or_description, schema=None, headers=None)[source]

Mark response field for view to view. There are two ways to use this decorator.

First, you can pass response object directly

@app.route('/users/<user_id>')
@mark.response(200, {
    'description': "Target user.",
    'schema': {
        'properties': {
            'name': {'type': 'string'},
        },
    }
})
def user_read(user_id):
    ...

Or you can pass each field of response.

@app.route('/post/<post_id>')
@mark.response(200, "Target post", post_schema, read_headers)
def post_read(post_id):
    ...

schema can be marshmallow’s Schema if marshmallow_jsonschema is installed.

schema(schema, in_='formData')[source]

Convert json schema to parameter and mark it to view.

set_swag(fn, swag)[source]
simple_param(in_, name, python_type, optional=False, **kwargs)[source]

Mark parameter with python type that can be converted by get_type_base()

summary(summary: str)[source]

Mark summary to view.

summary_from_docstring(fn)[source]

Mark summary from docstring.

swag(spec)[source]
update_swag(fn, swag)[source]

flask_swag.schemas module

schemas

Definitions of marshmallow schema for swagger specs.

class flask_swag.schemas.ContactSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Contact object schema

See http://swagger.io/specification/#contactObject

email = None

email

name = None

Name

opts = <marshmallow.schema.SchemaOpts object>
url = None

URL

class flask_swag.schemas.ExternalDocumentationSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

External documentation object schema

See http://swagger.io/specification/#externalDocumentationObject

description = None

Description

opts = <marshmallow.schema.SchemaOpts object>
url = None

URL

class flask_swag.schemas.HeaderSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Header object schema

See http://swagger.io/specification/#headerObject

collection_format = None

How to format collection

description = None

Description of the header

enum = None

Enum of available values

examples = None

Examples

exclusive_maximum = None

Exclusive maximum

exclusive_minimum = None

Exclusive minimum

format = None

Format of parameter

items = None

Describe items in array (if type if array)

max_items = None

Maximum items

max_length = None

Maximum length

maximum = None

Maximum

min_items = None

Minimum items

min_length = None

Minimum length

minimum = None

Minimum

multiple_of = None

Multiple of number

opts = <marshmallow.schema.SchemaOpts object>
pattern = None

Pattern

type = None

Type of parameter

unique_items = None

Unique number of items

class flask_swag.schemas.InfoSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Swagger API metadata object schema.

See http://swagger.io/specification/#infoObject

contact = None

Contact info for API

description = None

Short description

license = None

License of API

opts = <marshmallow.schema.SchemaOpts object>
terms_of_service = None

Terms of service

title = None

Title of application

version = None

Version of API, not a version of swagger spec

class flask_swag.schemas.ItemsSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Items object schema

Limited subset of schema object.

See http://swagger.io/specification/#itemsObject

collection_format = None

How to format collection

default = None

Default value

enum = None

Enum of available values

exclusive_maximum = None

Exclusive maximum

exclusive_minimum = None

Exclusive minimum

format = None

Format of object type. See http://swagger.io/specification/#dataTypeFormat

items = None

If type is array

max_items = None

Maximum items

max_length = None

Maximum length

max_properties = None

Maximum properties

maximum = None

Maximum

min_items = None

Minimum items

min_length = None

Minimum length

min_properties = None

Minimum properties

minimum = None

Minimum

multiple_of = None

Multiple of number

opts = <marshmallow.schema.SchemaOpts object>
type = None

Type of object

unique_items = None

Unique number of items

class flask_swag.schemas.LicenseSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

License object schema

See http://swagger.io/specification/#licenseObject

name = None

Name

opts = <marshmallow.schema.SchemaOpts object>
url = None

URL

class flask_swag.schemas.MappingSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: marshmallow.schema.Schema

Marshmallow schema whose input is mapping object.

get_attribute(attr, obj, default)[source]
opts = <marshmallow.schema.SchemaOpts object>
class flask_swag.schemas.OperationSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Single API operation on path object schema

See http://swagger.io/specification/#operationObject

consumes = None

MIME types can be consumed

deprecated = None

Is deprecated operation?

description = None

Long description of operation

external_docs = None

Additional external document

operation_id = None

Optional unique ID for the operaion

opts = <marshmallow.schema.SchemaOpts object>
parameters = None

Parameters

produces = None

MIME types can be produced

responses = None

Map ofresponses of the operation The key is status code (int) or ‘default’

schemes = None

Schemes that is supported by this operation

summary = None

Short summary of operation should be less than 120 chars. But we’ll not define max length for capability.

tags = None

List of tags

class flask_swag.schemas.ParameterSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Parameter object schema

See http://swagger.io/specification/#parameterObject

allow_empty_value = None

Allows empty value?

collection_format = None

How to format collection

description = None

Brief description

enum = None

Enum of available values

exclusive_maximum = None

Exclusive maximum

exclusive_minimum = None

Exclusive minimum

format = None

Format of parameter

in_ = None

In where?

items = None

Describe items in array (if type if array)

max_items = None

Maximum items

max_length = None

Maximum length

maximum = None

Maximum

min_items = None

Minimum items

min_length = None

Minimum length

minimum = None

Minimum

multiple_of = None

Multiple of number

name = None

Parameter name

opts = <marshmallow.schema.SchemaOpts object>
pattern = None

Pattern

required = None

Is required field?

schema = None

Body’s schema

type = None

Type of parameter

unique_items = None

Unique number of items

class flask_swag.schemas.PathItemSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Path item object schema

See http://swagger.io/specification/#pathItemObject

delete = None

DELETE method for this path item

get = None

GET method for this path item

head = None

HEAD method for this path item

options = None

OPTIONS method for this path item

opts = <marshmallow.schema.SchemaOpts object>
parameters = None

Parameters

patch = None

PATCH method for this path item

post = None

POST method for this path item

put = None

PUT method for this path item

class flask_swag.schemas.ResponseSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Single response object schema

See http://swagger.io/specification/#responseObject

description = None

Description of response

headers = None

Headers of response

opts = <marshmallow.schema.SchemaOpts object>
schema = None

Response body’s structure

class flask_swag.schemas.SchemaSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Schema object schema

See http://swagger.io/specification/#schemaObject

additional_properties = None

Accepts additional properties?

all_of = None

Validate with all of these schemas

default = None

Default value

description = None

Description

discriminator = None

Add support for polymorphism

enum = None

Enum of available values

example = None

Free-form example of schema

exclusive_maximum = None

Exclusive maximum

exclusive_minimum = None

Exclusive minimum

external_docs = None

Additional external document for this schema

format = None

Format of object type. See http://swagger.io/specification/#dataTypeFormat

items = None

Items

max_items = None

Maximum items

max_length = None

Maximum length

max_properties = None

Maximum properties

maximum = None

Maximum

min_items = None

Minimum items

min_length = None

Minimum length

min_properties = None

Minimum properties

minimum = None

Minimum

multiple_of = None

Multiple of number

opts = <marshmallow.schema.SchemaOpts object>
pattern = None

Pattern

properties = None

Properties of schema

read_only = None

Is read-only?

ref = None

JSON reference

required = None

List of name of required field

title = None

Title

type = None

Type of object

unique_items = None

Unique number of items

xml = None

XML metadata

class flask_swag.schemas.SwaggerSchema(extra=None, only=(), exclude=(), prefix='', strict=False, many=False, context=None, load_only=(), dump_only=(), partial=False)[source]

Bases: flask_swag.schemas.MappingSchema

Root swagger document object schema.

See http://swagger.io/specification/#swaggerObject

base_path = None

Prefix of API URL. Must be started with /

consumes = None

MIME types can be consumed

definitions = None

Definitions

external_docs = None

Additional external document

host = None

Host address of API server

info = None

API Metadata

opts = <marshmallow.schema.SchemaOpts object>
parameters = None

Predefined parameters that can be reused

paths = None

Paths of API

produces = None

MIME types can be produced

responses = None

Predefined responses that can be reused

schemes = None

Schemes of API server

version = None

Swagger spec version.

flask_swag.utils module

flask_swag.utils.compose(last, *fn)[source]

Compose functions.

flask_swag.utils.get_type_base(python_type) → dict[source]

Get base schema for python type.

flask_swag.utils.merge(dest, src)[source]

Merge plain objects without mutation.

flask_swag.utils.normalize_indent(docstring)[source]

Normalized indent of docstring.

flask_swag.utils.parse_endpoint(endpoint)[source]

Parse endpoint into (blueprint, endpoint). blueprint can be None

Module contents

flask_swag

Flask extension that extracts swagger spec from flask app & provides Swagger UI.

class flask_swag.Swag(app: flask.app.Flask=None, extractor: flask_swag.extractor.base.Extractor=None, mark: flask_swag.mark.Mark=None, *args, **kwargs)[source]

Bases: object

Flask extension class for flask_swag.

This is plain flask extension. So, you can use it like

swag = Swag(app)

and also

swag = Swag(app)

# Init later
swag.init_app(app)

The extension requires following configurations.

  • SWAG_TITLE

    Title for swagger info.

  • SWAG_API_VERSION

    API version info.

Or you can provide core.Info instead of them.

To customize URL for swagger, use following configurations.

  • SWAG_BLUEPRINT_NAME

    Default is 'swag'

  • SWAG_URL_PREFIX

    Default is '/swagger'

  • SWAG_JSON_URL

    Default is '/swagger.json'

  • SWAG_UI_PREFIX

    Default is '/ui'

And you can use another version of swagger-ui using configuration.

  • SWAG_UI_ROOT
generate_swagger(app: flask.app.Flask=<LocalProxy unbound>, swagger_info=None, swagger_fields=None, swag_blueprint='swag', extractor_kwargs=None)[source]

Generate swagger spec from app.

Parameters:
  • app – the flask app.
  • swagger_infoinfo field in swagger root object.
  • swagger_fields – extra fields in swagger root object.
  • swag_blueprint – the name of Flask-Swag blueprint
Extractor_kwargs:
 

kwargs to be passed to extractor’s extract_paths()

init_app(app, swagger_info=None, swagger_fields=None)[source]

Init flask app for Flask-Swag.

inject_swagger_url(html, url)[source]

Change default swagger URL by injecting javascript code into html.

make_blueprint(blueprint_name, swagger_ui_root, json_url, ui_prefix) → flask.blueprints.Blueprint[source]

Create a new Swagger UI related blueprint.

Parameters:
  • blueprint_name – name of the blueprint. default is ‘swag’
  • swagger_ui_root – root path for swagger-ui.
  • json_url – swagger spec json URL.
  • ui_prefix – prefix URL for swagger-ui
register_blueprint(app: flask.app.Flask) → flask.blueprints.Blueprint[source]

Register Swagger UI related blueprint.

Parameters:
  • blueprint_name – name of the blueprint. default is ‘swag’
  • prefix – URL prefix of the blueprint.
Returns:

created blueprint