Bug fixes:
CVE-2020-7965: Don’t attempt to parse JSON if the request’s Content-Type is mismatched.
Bug fixes:
Handle UnicodeDecodeError
when parsing JSON payloads (#427).
Thanks @lindycoder for the catch and patch.
Changes:
Use explicit type check for fields.DelimitedList
when deciding to
parse value with getlist()
(#406 (comment) ).
Support:
Add “Parsing Lists in Query Strings” section to docs (#406).
Features:
Add "path"
location to AIOHTTPParser
, FlaskParser
, and
PyramidParser
(#379). Thanks @zhenhua32 for the PR.
Add webargs.__version_info__
.
Features:
Make the schema class used when generating a schema from a dict overridable (#375). Thanks @ThiefMaster.
Bug fixes:
CVE-2019-9710: Fix race condition between parallel requests when the cache is used (#371). Thanks @ThiefMaster for reporting and fixing.
Bug fixes:
Remove lingering usages of ValidationError.status_code
(#365). Thanks @decaz for reporting.
Avoid AttributeError
on Python<3.5.4 (#366).
Fix incorrect type annotations for error_headers
.
Fix outdated docs (#367). Thanks @alexandersoto for reporting.
Bug fixes:
Fix installing simplejson
on Python 2 by
distributing a Python 2-only wheel (#363).
Features:
Error handlers for AsyncParser
classes may be coroutine functions.
Add type annotations to AsyncParser
and AIOHTTPParser
.
Bug fixes:
Features:
Backwards-incompatible: A 400 HTTPError is raised when an invalid JSON payload is passed. (#329). Thanks @zedrdave for reporting.
Other changes:
Backwards-incompatible: webargs.argmap2schema
is removed. Use
webargs.dict2schema
instead.
Backwards-incompatible: webargs.ValidationError
is removed.
Use marshmallow.ValidationError
instead.
# <5.0.0
from webargs import ValidationError
def auth_validator(value):
# ...
raise ValidationError("Authentication failed", status_code=401)
@use_args({"auth": fields.Field(validate=auth_validator)})
def auth_view(args):
return jsonify(args)
# >=5.0.0
from marshmallow import ValidationError
def auth_validator(value):
# ...
raise ValidationError("Authentication failed")
@use_args({"auth": fields.Field(validate=auth_validator)}, error_status_code=401)
def auth_view(args):
return jsonify(args)
Backwards-incompatible: Missing arguments will no longer be filled
in when using @use_kwargs
(#342, #307, #252). Use **kwargs
to account for non-required fields.
# <5.0.0
@use_kwargs(
{"first_name": fields.Str(required=True), "last_name": fields.Str(required=False)}
)
def myview(first_name, last_name):
# last_name is webargs.missing if it's missing from the request
return {"first_name": first_name}
# >=5.0.0
@use_kwargs(
{"first_name": fields.Str(required=True), "last_name": fields.Str(required=False)}
)
def myview(first_name, **kwargs):
# last_name will not be in kwargs if it's missing from the request
return {"first_name": first_name}
simplejson is now a required dependency on Python 2 (#334). This ensures consistency of behavior across Python 2 and 3.
Bug fixes:
Remove usages of argmap2schema
from fields.Nested
,
AsyncParser
, and PyramidParser
.
Add force_all
param to PyramidParser.use_args
.
Add warning about missing arguments to AsyncParser
.
Deprecation: Add warning about missing arguments getting added to parsed arguments dictionary (#342). This behavior will be removed in version 5.0.0.
Features:
Add force_all
argument to use_args
and use_kwargs
(#252, #307). Thanks @piroux for reporting.
Deprecation: The status_code
and headers
arguments to ValidationError
are deprecated. Pass error_status_code
and error_headers
to
Parser.parse
, Parser.use_args
, and Parser.use_kwargs
instead.
(#327, #336).
Custom error handlers receive error_status_code
and error_headers
arguments.
(#327).
# <4.2.0
@parser.error_handler
def handle_error(error, req, schema):
raise CustomError(error.messages)
class MyParser(FlaskParser):
def handle_error(self, error, req, schema):
# ...
raise CustomError(error.messages)
# >=4.2.0
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
# OR
@parser.error_handler
def handle_error(error, **kwargs):
raise CustomError(error.messages)
class MyParser(FlaskParser):
def handle_error(self, error, req, schema, status_code, headers):
# ...
raise CustomError(error.messages)
# OR
def handle_error(self, error, req, **kwargs):
# ...
raise CustomError(error.messages)
Legacy error handlers will be supported until version 5.0.0.
Bug fixes:
Bug fixes:
Fix bug in AIOHTTPParser
that caused a JSONDecode
error
when parsing empty payloads (#229). Thanks @explosic4
for reporting and thanks user @kochab for the PR.
Features:
Add webargs.testing
module, which exposes CommonTestCase
to third-party parser libraries (see comments in #287).
Features:
Backwards-incompatible: Custom error handlers receive the
marshmallow.Schema
instance as the third argument. Update any
functions decorated with Parser.error_handler
to take a schema
argument, like so:
# 3.x
@parser.error_handler
def handle_error(error, req):
raise CustomError(error.messages)
# 4.x
@parser.error_handler
def handle_error(error, req, schema):
raise CustomError(error.messages)
See marshmallow-code/marshmallow#840 (comment) for more information about this change.
Bug fixes:
Backwards-incompatible: Rename webargs.async
to
webargs.asyncparser
to fix compatibility with Python 3.7
(#240). Thanks @Reskov for the catch and patch.
Other changes:
Backwards-incompatible: Drop support for Python 3.4 (#243). Python 2.7 and >=3.5 are supported.
Backwards-incompatible: Drop support for marshmallow<2.15.0. marshmallow>=2.15.0 and >=3.0.0b12 are officially supported.
Use black with pre-commit for code formatting (#244).
Bug fixes:
Respect Parser.DEFAULT_VALIDATION_STATUS
when a status_code
is not
explicitly passed to ValidationError
(#180). Thanks @foresmac for
finding this.
Support:
Add “Returning HTTP 400 Responses” section to docs (#180).
Changes:
Backwards-incompatible: Custom error handlers receive the request object as the second
argument. Update any functions decorated with Parser.error_handler
to take a req
argument, like so:
# 2.x
@parser.error_handler
def handle_error(error):
raise CustomError(error.messages)
# 3.x
@parser.error_handler
def handle_error(error, req):
raise CustomError(error.messages)
Backwards-incompatible: Remove unused instance
and kwargs
arguments of argmap2schema
.
Backwards-incompatible: Remove Parser.load
method (Parser
now calls Schema.load
directly).
These changes shouldn’t affect most users. However, they might break custom parsers calling these methods. (#222)
Drop support for aiohttp<3.0.0.
Changes:
Features:
Deprecations:
Support for aiohttp<2.0.0 is deprecated and will be removed in webargs 2.0.0.
Changes:
HTTPExceptions
raised with webargs.flaskparser.abort
will always
have the data
attribute, even if no additional keywords arguments
are passed (#184). Thanks @lafrech.
Support:
Fix examples in examples/ directory.
Bug fixes:
Fix behavior of AIOHTTPParser.use_args
when as_kwargs=True
is passed with a Schema
(#179). Thanks @Itayazolay.
Features:
AIOHTTPParser
supports class-based views, i.e. aiohttp.web.View
(#177). Thanks @daniel98321.
Features:
Support:
Fix Flask error handling docs in “Framework support” section (#168). Thanks @nebularazer.
Bug fixes:
Bug fixes:
Fix compatibility with marshmallow 3.x.
Other changes:
Drop support for Python 2.6 and 3.3.
Support marshmallow>=2.7.0.
Bug fixes:
Port fix from release 1.5.2 to AsyncParser
. This fixes #146 for AIOHTTPParser
.
Handle invalid types passed to DelimitedList
(#149). Thanks @psconnect-dev for reporting.
Bug fixes:
Don’t add marshmallow.missing
to original_data
when using marshmallow.validates_schema(pass_original=True)
(#146). Thanks @lafrech for reporting and for the fix.
Other changes:
Test against Python 3.6.
Bug fixes:
Features:
The use_args
and use_kwargs
decorators add a reference to the undecorated function via the __wrapped__
attribute. This is useful for unit-testing purposes (#144). Thanks @EFF for the PR.
Bug fixes:
Bug fixes:
Prevent error when rendering validation errors to JSON in Flask (e.g. when using Flask-RESTful) (#122). Thanks @frol for the catch and patch. NOTE: Though this is a bugfix, this is a potentially breaking change for code that needs to access the original ValidationError
object.
# Before
@app.errorhandler(422)
def handle_validation_error(err):
return jsonify({"errors": err.messages}), 422
# After
@app.errorhandler(422)
def handle_validation_error(err):
# The marshmallow.ValidationError is available on err.exc
return jsonify({"errors": err.exc.messages}), 422
Bug fixes:
Fix behavior for nullable List fields (#107). Thanks @shaicantor for reporting.
Bug fixes:
Bug fixes:
Fix memory leak when calling parser.parse
with a dict
in a view (#101). Thanks @frankslaughter for reporting.
aiohttpparser: Fix bug in handling bulk-type arguments.
Support:
Massive refactor of tests (#98).
Docs: Fix incorrect use_args example in Tornado section (#100). Thanks @frankslaughter for reporting.
Docs: Add “Mixing Locations” section (#90). Thanks @tuukkamustonen.
Features:
Add bulk-type arguments support for JSON parsing by passing many=True
to a Schema
(#81). Thanks @frol.
Bug fixes:
Fix JSON parsing in Flask<=0.9.0. Thanks @brettdh for the PR.
Fix behavior of status_code
argument to ValidationError
(#85). This requires marshmallow>=2.7.0. Thanks @ParthGandhi for reporting.
Support:
Bug fixes:
aiohttpparser: Fix bug that raised a JSONDecodeError
raised when parsing non-JSON requests using default locations
(#80). Thanks @leonidumanskiy for reporting.
Fix parsing JSON requests that have a vendor media type, e.g. application/vnd.api+json
.
Features:
Parser.parse
, Parser.use_args
and Parser.use_kwargs
can take a Schema factory as the first argument (#73). Thanks @DamianHeard for the suggestion and the PR.
Support:
Features:
Add AIOHTTPParser
(#71).
Add webargs.async
module with AsyncParser
.
Bug fixes:
If an empty list is passed to a List argument, it will be parsed as an empty list rather than being excluded from the parsed arguments dict (#70). Thanks @mTatcher for catching this.
Other changes:
Backwards-incompatible: When decorating resource methods with FalconParser.use_args
, the parsed arguments dictionary will be positioned after the request and response arguments.
Backwards-incompatible: When decorating views with DjangoParser.use_args
, the parsed arguments dictionary will be positioned after the request argument.
Backwards-incompatible: Parser.get_request_from_view_args
gets passed a view function as its first argument.
Backwards-incompatible: Remove logging from default error handlers.
Features:
Add FalconParser
(#63).
TornadoParser
will parse json with simplejson
if it is installed.
BottleParser
caches parsed json per-request for improved performance.
No breaking changes. Yay!
Features:
TornadoParser
returns unicode strings rather than bytestrings (#41). Thanks @thomasboyt for the suggestion.
Add Parser.get_default_request
and Parser.get_request_from_view_args
hooks to simplify Parser
implementations.
Backwards-compatible: webargs.core.get_value
takes a Field
as its last argument. Note: this is technically a breaking change, but this won’t affect most users since get_value
is only used internally by Parser
classes.
Support:
Add examples/annotations_example.py
(demonstrates using Python 3 function annotations to define request arguments).
Fix examples. Thanks @hyunchel for catching an error in the Flask error handling docs.
Bug fixes:
Correctly pass validate
and force_all
params to PyramidParser.use_args
.
The major change in this release is that webargs now depends on marshmallow for defining arguments and validation.
Your code will need to be updated to use Fields
rather than Args
.
# Old API
from webargs import Arg
args = {
"name": Arg(str, required=True),
"password": Arg(str, validate=lambda p: len(p) >= 6),
"display_per_page": Arg(int, default=10),
"nickname": Arg(multiple=True),
"Content-Type": Arg(dest="content_type", location="headers"),
"location": Arg({"city": Arg(str), "state": Arg(str)}),
"meta": Arg(dict),
}
# New API
from webargs import fields
args = {
"name": fields.Str(required=True),
"password": fields.Str(validate=lambda p: len(p) >= 6),
"display_per_page": fields.Int(missing=10),
"nickname": fields.List(fields.Str()),
"content_type": fields.Str(load_from="Content-Type"),
"location": fields.Nested({"city": fields.Str(), "state": fields.Str()}),
"meta": fields.Dict(),
}
Features:
Error messages for all arguments are “bundled” (#58).
Changes:
Backwards-incompatible: Replace Args
with marshmallow fields (#61).
Backwards-incompatible: When using use_kwargs
, missing arguments will have the special value missing
rather than None
.
TornadoParser
raises a custom HTTPError
with a messages
attribute when validation fails.
Bug fixes:
Fix required validation of nested arguments (#39, #51). These are fixed by virtue of using marshmallow’s Nested
field. Thanks @ewang and @chavz for reporting.
Support:
Updated docs.
Add examples/schema_example.py
.
Tested against Python 3.5.
Changes:
If a parsed argument is None
, the type conversion function is not called #54. Thanks @marcellarius.
Bug fixes:
Features:
Add parsing of matchdict
to PyramidParser
. Thanks @hartror.
Bug fixes:
Fix PyramidParser's
use_kwargs
method (#42). Thanks @hartror for the catch and patch.
Correctly use locations passed to Parser’s constructor when using use_args
(#44). Thanks @jacebrowning for the catch and patch.
Fix behavior of default
and dest
argument on nested Args
(#40 and #46). Thanks @stas.
Changes:
A 422 response is returned to the client when a ValidationError
is raised by a parser (#38).
Features:
Support for webapp2 via the webargs.webapp2parser
module. Thanks @Trii.
Store argument name on RequiredArgMissingError
. Thanks @stas.
Allow error messages for required validation to be overriden. Thanks again @stas.
Removals:
Remove source
parameter from Arg
.
Features:
Changes:
Add dest
parameter to Arg
constructor which determines the key to be added to the parsed arguments dictionary (#32).
Backwards-incompatible: Rename targets
parameter to locations
in Parser
constructor, Parser#parse_arg
, Parser#parse
, Parser#use_args
, and Parser#use_kwargs
.
Backwards-incompatible: Rename Parser#target_handler
to Parser#location_handler
.
Deprecation:
The source
parameter is deprecated in favor of the dest
parameter.
Bug fixes:
Fix validate
parameter of DjangoParser#use_args
.
When parsing a nested Arg
, filter out extra arguments that are not part of the Arg's
nested dict
(#28). Thanks Derrick Gilland for the suggestion.
Fix bug in parsing Args
with both type coercion and multiple=True
(#30). Thanks Steven Manuatu for reporting.
Raise RequiredArgMissingError
when a required argument is missing on a request.
Fix behavior of multiple=True
when nesting Args (#29). Thanks Derrick Gilland for reporting.
Pyramid support thanks to @philtay.
User-friendly error messages when Arg
type conversion/validation fails. Thanks Andriy Yurchuk.
Allow use
argument to be a list of functions.
Allow Args
to be nested within each other, e.g. for nested dict validation. Thanks @saritasa for the suggestion.
Backwards-incompatible: Parser will only pass ValidationErrors
to its error handler function, rather than catching all generic Exceptions.
Backwards-incompatible: Rename Parser.TARGET_MAP
to Parser.__target_map__
.
Add a short-lived cache to the Parser
class that can be used to store processed request data for reuse.
Docs: Add example usage with Flask-RESTful.
Fix bug in TornadoParser
that raised an error when request body is not a string (e.g when it is a Future
). Thanks Josh Carp.
Fix Parser.use_kwargs
behavior when an Arg
is allowed missing. The allow_missing
attribute is ignored when use_kwargs
is called.
default
may be a callable.
Allow ValidationError
to specify a HTTP status code for the error response.
Improved error logging.
Add 'query'
as a valid target name.
Allow a list of validators to be passed to an Arg
or Parser.parse
.
A more useful __repr__
for Arg
.
Add examples and updated docs.
Add source
parameter to Arg
constructor. Allows renaming of keys in the parsed arguments dictionary. Thanks Josh Carp.
FlaskParser's
handle_error
method attaches the string representation of validation errors on err.data['message']
. The raised exception is stored on err.data['exc']
.
Additional keyword arguments passed to Arg
are stored as metadata.
Fix bug in TornadoParser's
handle_error
method. Thanks Josh Carp.
Add error
parameter to Parser
constructor that allows a custom error message to be used if schema-level validation fails.
Fix bug that raised a UnicodeEncodeError
on Python 2 when an Arg’s validator function received non-ASCII input.
Fix regression with parsing an Arg
with both default
and target
set (see issue #11).
Add validate
parameter to Parser.parse
and Parser.use_args
. Allows validation of the full parsed output.
If allow_missing
is True
on an Arg
for which None
is explicitly passed, the value will still be present in the parsed arguments dictionary.
Backwards-incompatible: Parser's
parse_*
methods return webargs.core.Missing
if the value cannot be found on the request. NOTE: webargs.core.Missing
will not show up in the final output of Parser.parse
.
Fix bug with parsing empty request bodies with TornadoParser
.
Fix behavior of Arg's
allow_missing
parameter when multiple=True
.
Fix bug in tornadoparser that caused parsing JSON arguments to fail.
Fix JSON parsing in Flask parser when Content-Type header contains more than just application/json
. Thanks Samir Uppaluru for reporting.
Backwards-incompatible: The use
parameter to Arg
is called before type conversion occurs. Thanks Eric Wang for the suggestion.
Tested on Tornado>=4.0.
Custom target handlers can be defined using the Parser.target_handler
decorator.
Error handler can be specified using the Parser.error_handler
decorator.
Args
can define their request target by passing in a target
argument.
Backwards-incompatible: DEFAULT_TARGETS
is now a class member of Parser
. This allows subclasses to override it.
Fix bug that caused use_args
to fail on class-based views in Flask.
Add allow_missing
parameter to Arg
.
Awesome contributions from the open-source community!
Add use_kwargs
decorator. Thanks @venuatu.
Tornado support thanks to @jvrsantacruz.
Tested on Python 3.4.
Fix bug with parsing JSON in Flask and Bottle.
Remove print statements in core.py. Oops.
Add support for repeated parameters (#1).
Backwards-incompatible: All parse_*
methods take arg
as their fourth argument.
Add error_handler
param to Parser
.
Bottle support.
Add targets
param to Parser
. Allows setting default targets.
Add files
target.
First release.
Parses JSON, querystring, forms, headers, and cookies.
Support for Flask and Django.