API Reference¶
- flask_smorest.abort(http_status_code: int, exc: Exception | None = None, **kwargs: Any) NoReturn [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_smorest.Api(app=None, *, spec_kwargs=None, config_prefix='')[source]¶
Main class
Provides helpers to build a REST API using Flask.
- Parameters:
app (Flask) – Flask application
spec_kwargs – kwargs to pass to internal APISpec instance
config_prefix (str) – Prefix to Api parameters in application config
The
spec_kwargs
dictionary is passed as kwargs to the internal APISpec instance. flask-smorest adds a few parameters to the original parameters documented inapispec.APISpec
:- Parameters:
flask_plugin (apispec.BasePlugin) – Flask plugin
marshmallow_plugin (apispec.BasePlugin) – Marshmallow plugin
extra_plugins (list|tuple) – List of additional
BasePlugin
instancestitle (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
- Parameters:
converter (BaseConverter) – Converter Subclass of werkzeug’s BaseConverter
func (callable) – Function returning a parameter schema from a converter intance
Example:
# 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 api.register_converter( ObjectIdConverter, objectidconverter2paramschema ) @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 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 toa 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 ('string, 'date-time') passing a marshmallow Field api.register_field(CustomDateTime, ma.fields.DateTime)
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, anHTTPException
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
. Thisabort
allows the caller to pass kwargs and stores them inexception.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
- errors (
headers (
dict
): additional headers
- init_app(app, *, spec_kwargs=None)[source]¶
Initialize Api with application
- Parameters:
spec_kwargs – kwargs to pass to internal APISpec instance. Updates
spec_kwargs
passed inApi
init.
Blueprint¶
- 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
- 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
orfiles
location. The default value depends on the location and is set inBlueprint.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 (dict) – Parameter examples.
kwargs – 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, *, content_type=None, description=None, example=None, examples=None, headers=None)¶
Decorator generating an endpoint response
- Parameters:
status_code (int|str|HTTPStatus) – HTTP status code. Used if none is returned from the view function.
schema|str|dict (schema) –
Schema
class or instance or reference or dict. If not None, will be used to serialize response data.content_type (str) – Content type of the response.
description (str) – Description of the response (default: None).
example (dict) – Example of response message.
examples (dict) – 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, theschema
andstatus_code
parameters are only used to document the resource. Only in this case,schema
may be a reference as string or a schema definition as dict.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.
- alt_response(status_code, response=None, *, schema=None, content_type=None, description=None, example=None, examples=None, headers=None, success=False)¶
Decorator documenting an alternative response
- Parameters:
status_code (int|str|HTTPStatus) – HTTP status code.
response (str) – Response reference.
schema|str|dict (schema) –
Schema
class or instance or reference or dict.description (str) – Description of the response (default: None).
example (dict) – Example of response message.
examples (dict) – Examples of response message.
headers (dict) – Headers returned by the response.
success (bool) –
True
if this response is part of the normal flow of the function. Default:False
.
This decorator allows the user to document an alternative response. This can be an error managed with
abort
or any response that is not the primary flow of the function documented byBlueprint.response
.When a response reference is passed as
response
, it is used as description and the keyword arguments are ignored. Otherwise, a description is built from the keyword arguments.
- paginate(pager=None, *, page=None, page_size=None, max_page_size=None)¶
Decorator adding pagination to the endpoint
- Parameters:
pager (type[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(obj)¶
Decorator adding ETag management to the endpoint
The
etag
decorator expects the decorated view function to return aResponse
object. It is the case if it is decorated with theresponse
decorator.The
etag
decorator may be used to decorate aMethodView
. In this case, it applies to all HTTP methods in theMethodView
.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 ifset_etag
is not called.Issues a warning if called in a method other than GET, HEAD, POST, PUT or PATCH.
- add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, *, parameters=None, tags=None, **options)[source]¶
Register url rule in application
Also stores doc info for later registration
Use this to register 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).
view_func (callable|MethodView) – View function or MethodView class
parameters (list) – List of parameter descriptions relevant to all operations in this path. Only used to document the resource.
tags (list) – List of tags for the resource. If None,
Blueprint
name is used.options – Options to be forwarded to the underlying
werkzeug.routing.Rule
object.
- 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_blueprint(blueprint, **options)[source]¶
Register a nested blueprint in application
Also stores doc info from the nested bluepint for later registration.
Use this to register a nested
Blueprint
.- Parameters:
blueprint (Blueprint) – Blueprint to register under this blueprint.
options – Options to be forwarded to the underlying
flask.Blueprint.register_blueprint()
method.
- register_views_in_doc(api, app, spec, *, name, parameters)[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, tags=None, **options)[source]¶
Decorator to register view function in application and documentation
Calls
add_url_rule
.
Pagination¶
Fields¶
Custom marshmallow fields