In APIFlask (marshmallow), the process of parsing and validating the input request data
is called deserialization (we load the data from the request). And the process of
formatting the output response data is called serialization (we dump the data to
the response).
Notice we use the "load" and "dump" to represent these two processes. When creating
the schema, we set the default value for the fields in the input schema with the load_default
parameter, and we use the dump_default parameter to set the default value for fields
in the output schema.
There are four decorators to register callback methods in the load/dump processes:
pre_load: to register a method to invoke before parsing/validating the request data
post_load: to register a method to invoke after parsing/validating the request data
pre_dump: to register a method to invoke before formatting the return value of the view function
post_dump: to register a method to invoke after formatting the return value of the view function
And there are two decorators to register a validation method:
validates(field_name): to register a method to validate a specified field
validates_schema: to register a method to validate the whole schema
Tip
When using the validates_schema, notice the skip_on_field_errors is set to True as default:
If skip_on_field_errors=True, this validation method will be skipped whenever validation errors
have been detected when validating fields.
Import these decorators directly from marshmallow:
APIFlask's apiflask.fields module includes all the data fields from marshmallow, webargs, and
Flask-Marshmallow. We recommend importing them from the apiflask.fields module:
APIFlask's aipflask.validators contains all the validator class provided by marshmallow
and two extra validators FileType and FileSize provided by flask-marshmallow:
The OpenAPI schema name of each schema is resolved based on a resolver function, here is
the default schema name resolver used in APIFlask:
defschema_name_resolver(schema):name=schema.__class__.__name__# get schema class nameifschema.partial:# add a "Update" suffix for partial schemaname+='Update'returnname
You can provide a custom schema name resolver by setting the APIFlask.schema_name_resolver
attribute:
fromapiflaskimportAPIFlaskdefmy_schema_name_resolver(schema):name=schema.__class__.__name__ifname.endswith('Schema'):# remove the "Schema" suffixname=name[:-6]ornameifschema.partial:name+='Partial'returnnameapp=APIFlask(__name__)app.schema_name_resolver=my_schema_name_resolver
The schema name resolver should accept the schema object as argument and return the name.
When you set up the output of a view function with the output decorator, you need to
return the object or dict that matches the schema you passed to the output decorator. Then,
APIFlask will serialize the return value to response body:
{"id":2,"name":"Kitty","category":"cat"}
However, You may want to insert the output data into a data field and add some meta fields.
So that you can return a unified response for all endpoints. For example, make all the
responses to the following format:
To achieve this, you will need to set a base response schema, then pass it to the configuration variable
BASE_RESPONSE_SCHEMA:
fromapiflaskimportAPIFlask,Schemafromapiflask.fieldsimportString,Integer,Fieldapp=APIFlask(__name__)classBaseResponse(Schema):data=Field()# the data keymessage=String()code=Integer()app.config['BASE_RESPONSE_SCHEMA']=BaseResponse
The default data key is "data", you can change it to match your data field name in your schema
via the configuration variable BASE_RESPONSE_DATA_KEY:
app.config['BASE_RESPONSE_DATA_KEY ']='data'
Now you can return a dict matches the base response schema in your view functions:
With marshmalow-dataclass, you can define
dataclasses and then convert them into marshmallow schemas.
$pipinstallmarshmallow-dataclass
You can use the dataclass decorator from marshmallow-dataclass to create the data class, then call the
.Schema attribute to get the corresponding marshmallow schema: