API Reference

flask_rest_api.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.

Api

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

Main class

Provides helpers to build a REST API using Flask.

Parameters:
  • 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-rest-api adds a few parameters to the original parameters documented in apispec.APISpec:

Parameters:
  • flask_plugin (apispec.BasePlugin) – Flask plugin
  • marshmallow_plugin (apispec.BasePlugin) – Marshmallow plugin
  • extra_plugins (list|tuple) – List of additional BasePlugin instances
  • 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.

title and version APISpec parameters can’t be passed here, they are set according to the app configuration.

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

register_converter(converter, conv_type, conv_format=None)

Register custom path parameter converter

Parameters:
  • converter (BaseConverter) – Converter Subclass of werkzeug’s BaseConverter
  • conv_type (str) – Parameter type
  • conv_format (str) – Parameter format (optional)

Example:

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

# Register converter in Api
api.register_converter(ObjectIdConverter, 'string', 'ObjectID')

@blp.route('/pets/{objectid:pet_id}')
    ...

api.register_blueprint(blp)

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

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)

Examples:

# 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 ('integer, 'int32') passing a code marshmallow field
api.register_field(CustomInteger, ma.fields.Integer)

Should be called before registering schemas with schema.

handle_http_exception(error)

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_rest_api 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

register_blueprint(blp, **options)[source]

Register a blueprint in the application

Also registers documentation for the blueprint/resource

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

Must be called after app is initialized.

Blueprint

class flask_rest_api.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

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(schema=None, *, code=200, description=None, example=None, examples=None, headers=None)

Decorator generating an endpoint response

Parameters:
  • schemaSchema class or instance. If not None, will be used to serialize response data.
  • code (int|str|HTTPStatus) – HTTP status code (default: 200). Used if none is returned from the view function.
  • 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 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

Parameters:
  • 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.

etag(etag_schema=None)

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:

Example:

@blp.etag
def view_func(...):
    ...

@blp.etag(EtagSchema)
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 logged at runtime if this function was not called.

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.

Logs a warning if called in a method other than one of GET, HEAD, POST, PUT, PATCH.

static doc(**kwargs)[source]

Decorator adding description attributes to a view function

Values passed as kwargs are copied verbatim in the docs

Example:

@blp.doc(description="Return pets based on ID",
         summary="Find pets by ID"
)
def get(...):
    ...
register_views_in_doc(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.

Parameters:
  • 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.

Fields

Custom marshmallow fields

class flask_rest_api.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.