API Reference

flask_smorest.abort(http_status_code, exc=None, **kwargs)[source]

Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.

From Flask-Restful. See NOTICE file for license information.


class flask_smorest.Api(app=None, *, spec_kwargs=None)[source]

Main class

Provides helpers to build a REST API using Flask.

  • app (Flask) – Flask application
  • spec_kwargs (dict) – kwargs to pass to internal APISpec instance

The spec_kwargs dictionary is passed as kwargs to the internal APISpec instance. flask-smorest adds a few parameters to the original parameters documented in apispec.APISpec:

  • flask_plugin (apispec.BasePlugin) – Flask plugin
  • marshmallow_plugin (apispec.BasePlugin) – Marshmallow plugin
  • extra_plugins (list|tuple) – List of additional BasePlugin instances
  • title (str) – API title. Can also be passed as application parameter API_TITLE.
  • version (str) – API version. Can also be passed as application parameter API_VERSION.
  • openapi_version (str) – OpenAPI version. Can also be passed as application parameter OPENAPI_VERSION.

This allows the user to override default Flask and marshmallow plugins.

For more flexibility, additional spec kwargs can also be passed as app parameter API_SPEC_OPTIONS.

register_converter(converter, func)

Register custom path parameter converter

  • converter (BaseConverter) – Converter Subclass of werkzeug’s BaseConverter
  • func (callable) – Function returning a parameter schema from a converter intance


# Register MongoDB's ObjectId converter in Flask application
app.url_map.converters['objectid'] = ObjectIdConverter

# Define custom converter to schema function
def objectidconverter2paramschema(converter):
    return {'type': 'string', 'format': 'ObjectID'}

# Register converter in Api



Once the converter is registered, all paths using it will have corresponding path parameter documented with the right schema.

Should be called before registering paths with Blueprint.route.

register_field(field, *args)

Register custom Marshmallow field

Registering the Field class allows the Schema parser to set the proper type and format when documenting parameters from Schema fields.

Parameters:field (Field) – Marshmallow Field class

*args can be:

  • a pair of the form (type, format) to map to
  • a core marshmallow field type (then that type’s mapping is used)


# Map to ('string', 'ObjectId') passing type and format
api.register_field(ObjectId, 'string', 'ObjectId')

# Map to ('string', ) passing type
api.register_field(CustomString, 'string', None)

# Map to ('string, 'date-time') passing a marshmallow Field
api.register_field(CustomDateTime, ma.fields.DateTime)

Should be called before registering schemas with schema.


Return a JSON response containing a description of the error

This method is registered at app init to handle HTTPException.

  • When abort is called in the code, an HTTPException is triggered and Flask calls this handler.
  • When an exception is not caught in a view, Flask makes it an InternalServerError and calls this handler.

flask-smorest republishes webargs’s abort. This abort allows the caller to pass kwargs and stores them in exception.data so that the error handler can use them to populate the response payload.

Extra information expected by this handler:

  • message (str): a comment
  • errors (dict): errors, typically validation errors in
    parameters and request body
  • headers (dict): additional headers
init_app(app, *, spec_kwargs=None)[source]

Initialize Api with application

Parameters:spec_kwargs (dict) – kwargs to pass to internal APISpec instance. Updates spec_kwargs passed in Api init.
register_blueprint(blp, **options)[source]

Register a blueprint in the application

Also registers documentation for the blueprint/resource

  • blp (Blueprint) – Blueprint to register
  • options (dict) – Keyword arguments overriding Blueprint defaults

Must be called after app is initialized.


class flask_smorest.Blueprint(*args, **kwargs)[source]

Blueprint that registers info in API documentation

arguments(schema, *, location='json', content_type=None, required=True, description=None, example=None, examples=None, **kwargs)

Decorator specifying the schema used to deserialize parameters

  • schema (type|Schema) – Marshmallow Schema class or instance used to deserialize and validate the argument.
  • location (str) – Location of the argument.
  • content_type (str) – Content type of the argument. Should only be used in conjunction with json, form or files location. The default value depends on the location and is set in Blueprint.DEFAULT_LOCATION_CONTENT_TYPE_MAPPING. This is only used for documentation purpose.
  • required (bool) – Whether argument is required (default: True).
  • description (str) – Argument description.
  • example (dict) – Parameter example.
  • examples (list) – List of parameter examples.
  • kwargs (dict) – Keyword arguments passed to the webargs use_args decorator used internally.

The required and description only affect body arguments (OpenAPI 2) or requestBody (OpenAPI 3), because the docs expose the whole schema. For other locations, the schema is turned into an array of parameters and the required/description value of each parameter item is taken from the corresponding field in the schema.

The example and examples parameters are mutually exclusive and should only be used with OpenAPI 3 and when location is json.

See Arguments.

response(status_code, schema=None, *, description=None, example=None, examples=None, headers=None)

Decorator generating an endpoint response

  • status_code (int|str|HTTPStatus) – HTTP status code. Used if none is returned from the view function.
  • schemaSchema class or instance. If not None, will be used to serialize response data.
  • description (str) – Description of the response (default: None).
  • example (dict) – Example of response message.
  • examples (list) – Examples of response message.
  • headers (dict) – Headers returned by the response.

The decorated function is expected to return the same types of value than a typical flask view function, except the body part may be an object or a list of objects to serialize with the schema, rather than a string.

If the decorated function returns a Response object, the schema and status_code parameters are only used to document the resource.

The example and examples parameters are mutually exclusive. The latter should only be used with OpenAPI 3.

The example, examples and headers parameters are only used to document the resource.

See Response.

paginate(pager=None, *, page=None, page_size=None, max_page_size=None)

Decorator adding pagination to the endpoint

  • pager (Page) – Page class used to paginate response data
  • page (int) – Default requested page number (default: 1)
  • page_size (int) – Default requested page size (default: 10)
  • max_page_size (int) – Maximum page size (default: 100)

If a Page class is provided, it is used to paginate the data returned by the view function, typically a lazy database cursor.

Otherwise, pagination is handled in the view function.

The decorated function may return a tuple including status and/or headers, like a typical flask view function. It may not return a Response object.

See Pagination.


Decorator generating an endpoint response

Parameters:etag_schemaSchema class or instance. If not None, will be used to serialize etag data.

Can be used as either a decorator or a decorator factory:


def view_func(...):

def view_func(...):

The etag decorator expects the decorated view function to return a Response object. It is the case if it is decorated with the response decorator.

See ETag.

check_etag(etag_data, etag_schema=None)

Compare If-Match header with computed ETag

Raise 412 if If-Match header does not match.

Must be called from resource code to check ETag.

Unfortunately, there is no way to call it automatically. It is the developer’s responsability to do it. However, a warning is issued at runtime if this function was not called.

Issues a warning if called in a method other than PUT, PATCH, or DELETE.

set_etag(etag_data, etag_schema=None)

Set ETag for this response

Raise 304 if ETag identical to If-None-Match header

Must be called from resource code, unless the view function is decorated with the response decorator, in which case the ETag is computed by default from response data if set_etag is not called.

Issues a warning if called in a method other than GET, HEAD, POST, PUT or PATCH.

static doc(**kwargs)[source]

Decorator adding description attributes to a view function

Values passed as kwargs are copied verbatim in the docs


@blp.doc(description="Return pets based on ID",
         summary="Find pets by ID"
def get(...):
register_views_in_doc(api, app, spec)[source]

Register views information in documentation

If a schema in a parameter or a response appears in the spec schemas section, it is replaced by a reference in the parameter or response documentation:

“schema”:{“$ref”: “#/components/schemas/MySchema”}

route(rule, *, parameters=None, **options)[source]

Decorator to register url rule in application

Also stores doc info for later registration

Use this to decorate a MethodView or a resource function.

  • rule (str) – URL rule as string.
  • endpoint (str) – Endpoint for the registered URL rule (defaults to function name).
  • parameters (list) – List of parameters relevant to all operations in this path, only used to document the resource.
  • options (dict) – Options to be forwarded to the underlying werkzeug.routing.Rule object.


Custom marshmallow fields

class flask_smorest.fields.Upload(format='binary', **kwargs)[source]

File upload field

Parameters:format (str) – File content encoding (binary, base64). Only relevant to OpenAPI 3. Only used for documentation purpose.