Features:
- Backwards-incompatible: Remove
__version__,__parsed_version__, and__version_info__constants from__init__.pyfile. Users should useimportlib.metadatainstead (:pr:`1024`).
Other changes:
- Backwards-incompatible: The
AsyncParserclass has been removed, sinceParsernow provides async functionality. Users should useawait parser.async_parse()to access the async features ofParser. - Backwards-incompatible: DelimitedList and DelimitedTuple fields have changed their default empty_value from the empty string ("") to missing. This allows nested fields with a load_default to be used to better customize behavior.
- Drop support for Python 3.9, which is EOL (:pr:`1019`).
- Drop support for Bottle < 0.13 (:pr:`1019`).
- Drop support for Flask < 3.1.0 (:pr:`1023`).
- Drop support for Django < 5.2.0 (:pr:`1023`).
- Drop support for Tornado < 6.5.0 (:pr:`1023`).
- Drop support for Pyramid < 2.0.2 (:pr:`1023`).
- Drop support for Falcon < 4.1.0 (:pr:`1023`).
- Drop support for aiohttp < 3.13.0 (:pr:`1023`).
- Drop support for marshmallow < 4.0.0 (:pr:`1023`).
Bug fixes:
- Correct the package metadata for
marshmallowversions which are supported bywebargs - Fix deprecation warning on Python 3.14 (:issue:`1013`). Thanks :user:`decaz` for reporting and for the PR.
Other changes:
- Test against Python 3.14 (:pr:`1016`).
Other changes:
- Test against Python 3.13 (:pr:`982`).
- Drop support for Python 3.8, which is EOL (:pr:`981`).
- Support marshmallow 4 (:pr:`987`).
Bug fixes:
- Fix the handling of invalid JSON bodies in the
bottleparser to supportbottleversions>=0.13(:pr:`974`).
Other changes:
MultiDictProxynow inherits fromMutableMappingrather thanMapping(:pr:`960`).
Other changes:
- Test against Python 3.12.
- Async location loading now supports loader functions which are not themselves
async, but which return an awaitable result. This means that users who are
already handling awaitable objects can return them from non-async loaders and
expect
webargstoawaitthem. This allows some async interactions with supported frameworks, where thewebargs-provided parser returns a framework object and the framework can be set to return awaitables, e.g., the Falcon parser. Thanks :user:`j0k2r` for the PR! (:pr:`935`)
Features:
- Add a new class attribute,
empty_valuetoDelimitedListandDelimitedTuple, with a default of"". This controls the value deserialized when an empty string is seen.
empty_value can be used to handle types other than strings more gracefully, e.g.
from webargs import fields
class IntList(fields.DelimitedList):
empty_value = 0
myfield = IntList(fields.Int())Note
empty_value will be changing in webargs v9.0 to be missing by
default. This will allow use of fields with load_default to specify
handling of the empty value.
- The rule for default argument names has been made configurable by overriding
the
get_default_arg_namemethod. This is described in the argument passing documentation.
Other changes:
- Drop support for Python 3.7, which is EOL.
- Type annotations for
FlaskParserhave been improved.
Features:
webargs.Parsernow inherits fromtyping.Genericand is parametrizable over the type of the request object. Various framework-specific parsers are parametrized over their relevant request object classes.webargs.Parserand its subclasses now support passing arguments as a single keyword argument without expanding the parsed data into its components. For more details, see advanced docs onArgument Passing and arg_name.
Other changes:
- Type annotations have been improved to allow
Mappingfor dict-like schemas where previouslydictwas used. This makes the type covariant rather than invariant (:issue:`836`). - Test against Python 3.11 (:pr:`787`).
Features:
- A new method,
webargs.Parser.async_parse, can be used for async-aware parsing from the base parser class. This can handle async location loader functions and async error handlers. webargs.Parser.use_argsanduse_kwargscan now be used to decorate async functions, and will useasync_parseif the decorated function is also async. They will call the non-asyncparsemethod when used to decorate non-async functions.- As a result of the changes to
webargs.Parser,FlaskParser,DjangoParser, andFalconParsernow all support async views. Thanks :user:`Isira-Seneviratne` for the initial PR.
Changes:
- The implementation of
AsyncParserhas changed. Now thatwebargs.Parserhas built-in support for async usage, the primary purpose ofAsyncParseris to redefineparseas an alias forasync_parse - Set
python_requires>=3.7.2in package metadata (:pr:`692`). Thanks :user:`kasium` for the PR.
Bug fixes:
- Fix publishing type hints per PEP-561. (:pr:`650`).
- Add DelimitedTuple to fields.__all__ (:pr:`678`).
- Narrow type of
argmapfromMappingtoDict(:pr:`682`).
Other changes:
- Test against Python 3.10 (:pr:`647`).
- Drop support for Python 3.6 (:pr:`673`).
- Address distutils deprecation warning in Python 3.10 (:pr:`652`). Thanks :user:`kkirsche` for the PR.
- Use postponed evaluation of annotations (:pr:`663`). Thanks :user:`Isira-Seneviratne` for the PR.
- Pin mypy version in tox (:pr:`674`).
- Improve type annotations for
__version_info__(:pr:`680`).
Bug fixes:
- Fix "
DelimitedListdeserializes empty string as['']" (:issue:`623`). Thanks :user:`TTWSchell` for reporting and for the PR.
Other changes:
- New documentation theme with furo. Thanks to :user:`pradyunsg` for writing furo!
- Webargs has a new logo. Thanks to :user:`michaelizergit`! (:issue:`312`)
- Don't build universal wheels. We don't support Python 2 anymore. (:pr:`632`)
- Make the build reproducible (:pr:`631`).
Features:
- Add Parser.pre_load as a method for allowing users to modify data before schema loading, but without redefining location loaders. See advanced docs on Parser pre_load for usage information. (:pr:`583`)
- Backwards-incompatible:
unknowndefaults to None for body locations (json, form and json_or_form) (:issue:`580`). - Detection of fields as "multi-value" for unpacking lists from multi-dict
types is now extensible with the
is_multipleattribute. If a field setsis_multiple = Trueit will be detected as a multi-value field. Ifis_multipleis not set or is set toNone, webargs will check if the field is an instance ofListorTuple. (:issue:`563`) - A new attribute on
Parserobjects,Parser.KNOWN_MULTI_FIELDScan be used to set fields which should be detected asis_multiple=Trueeven when the attribute is not set (:pr:`592`).
See docs on "Multi-Field Detection" for more details.
Bug fixes:
Tuplefield now behaves as a "multiple" field (:pr:`585`).
Bug fixes:
- Fix DelimitedList and DelimitedTuple to pass additional keyword arguments through their _serialize methods to the child fields and fix type checking on these classes. (:issue:`569`) Thanks to :user:`decaz` for reporting.
Changes:
- Backwards-incompatible: Drop support for webapp2 (:pr:`565`).
- Add type annotations to Parser class, DelimitedList, and DelimitedTuple. (:issue:`566`)
Features:
- DjangoParser now supports the headers location. (:issue:`540`)
- FalconParser now supports a new media location, which uses Falcon's media decoding. (:issue:`253`)
media behaves very similarly to the json location but also supports any registered media handler. See the Falcon documentation on media types for more details.
Changes:
- FalconParser defaults to the media location instead of json. (:issue:`253`)
- Test against Python 3.9 (:pr:`552`).
- Backwards-incompatible: Drop support for Python 3.5 (:pr:`553`).
Refactoring:
Backwards-incompatible: Remove support for marshmallow2 (:issue:`539`)
Backwards-incompatible: Remove dict2schema
Users desiring the dict2schema functionality may now rely upon marshmallow.Schema.from_dict. Rewrite any code using dict2schema like so:
import marshmallow as ma
# webargs 6.x and older
from webargs import dict2schema
myschema = dict2schema({"q1", ma.fields.Int()})
# webargs 7.x
myschema = ma.Schema.from_dict({"q1", ma.fields.Int()})Features:
- Add
unknownas a parameter toParser.parse,Parser.use_args,Parser.use_kwargs, and parser instantiation. When set, it will be passed toSchema.load. When not set, the value passed will depend on the parser's settings. If set toNone, the schema's default behavior will be used (i.e. no value is passed toSchema.load) and parser settings will be ignored.
This allows usages like
import marshmallow as ma
@parser.use_kwargs(
{"q1": ma.fields.Int(), "q2": ma.fields.Int()}, location="query", unknown=ma.EXCLUDE
)
def foo(q1, q2): ...- Defaults for
unknownmay be customized on parser classes viaParser.DEFAULT_UNKNOWN_BY_LOCATION, which maps location names to values to use.
Usages are varied, but include
import marshmallow as ma
from webargs.flaskparser import FlaskParser
# as well as...
class MyParser(FlaskParser):
DEFAULT_UNKNOWN_BY_LOCATION = {"query": ma.INCLUDE}
parser = MyParser()Setting the unknown value for a Parser instance has higher precedence. So
parser = MyParser(unknown=ma.RAISE)will always pass RAISE, even when the location is query.
- By default, webargs will pass
unknown=EXCLUDEfor all locations except for request bodies (json,form, andjson_or_form) and path parameters. Request bodies and path parameters will passunknown=RAISE. This behavior is defined by the default value forDEFAULT_UNKNOWN_BY_LOCATION.
Changes:
- Registered error_handler callbacks are required to raise an exception. If a handler is invoked and no exception is raised, webargs will raise a ValueError (:issue:`527`)
Bug fixes:
- Failure to validate flask headers would produce error data which contained tuples as keys, and was therefore not JSON-serializable. (:issue:`500`) These errors will now extract the headername as the key correctly. Thanks to :user:`shughes-uk` for reporting.
Features:
- Add
fields.DelimitedTuplewhen using marshmallow 3. This behaves as a combination offields.DelimitedListandmarshmallow.fields.Tuple. It takes an iterable of fields, plus a delimiter (defaults to,), and parses delimiter-separated strings into tuples. (:pr:`509`) - Add
__str__and__repr__to MultiDictProxy to make it easier to work with (:pr:`488`)
Support:
- Various docs updates (:pr:`482`, :pr:`486`, :pr:`489`, :pr:`498`, :pr:`508`). Thanks :user:`lefterisjp`, :user:`timgates42`, and :user:`ugultopu` for the PRs.
Features:
FalconParser: Pass request content length toreq.stream.readto provide compatibility withfalcon.testing(:pr:`477`). Thanks :user:`suola` for the PR.- Backwards-incompatible: Factorize the
use_args/use_kwargsbranch in all parsers. Whenas_kwargsisFalse, arguments are now consistently appended to the arguments list by theuse_argsdecorator. Before this change, thePyramidParserwould prepend the argument list on each call touse_args. Pyramid view functions must reverse the order of their arguments. (:pr:`478`)
Refactoring:
- Backwards-incompatible: Use keyword-only arguments (:pr:`472`).
Features:
- Backwards-incompatible: webargs will rewrite the error messages in ValidationErrors to be namespaced under the location which raised the error. The messages field on errors will therefore be one layer deeper with a single top-level key.
Refactoring:
- Remove the cache attached to webargs parsers. Due to changes between webargs v5 and v6, the cache is no longer considered useful.
Other changes:
- Import
Mappingfromcollections.abcin pyramidparser.py (:pr:`471`). Thanks :user:`tirkarthi` for the PR.
Refactoring:
- Backwards-incompatible: DelimitedList now requires that its input be a string and always serializes as a string. It can still serialize and deserialize using another field, e.g. DelimitedList(Int()) is still valid and requires that the values in the list parse as ints.
Bug fixes:
- :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched (bugfix from 5.5.3).
Features:
- Backwards-incompatible: Support Falcon 2.0. Drop support for Falcon 1.x (:pr:`459`). Thanks :user:`dodumosu` and :user:`Nateyo` for the PR.
Other changes:
- Backwards-incompatible: Drop support for Python 2 (:issue:`440`). Thanks :user:`hugovk` for the PR.
Features:
- Backwards-incompatible: Schemas will now load all data from a location, not only data specified by fields. As a result, schemas with validators which examine the full input data may change in behavior. The unknown parameter on schemas may be used to alter this. For example, unknown=marshmallow.EXCLUDE will produce a behavior similar to webargs v5.
Bug fixes:
- Backwards-incompatible: All parsers now require the Content-Type to be set
correctly when processing JSON request bodies. This impacts
DjangoParser,FalconParser,FlaskParser, andPyramidParser
Refactoring:
- Backwards-incompatible: Schema fields may not specify a location any longer, and Parser.use_args and Parser.use_kwargs now accept location (singular) instead of locations (plural). Instead of using a single field or schema with multiple locations, users are recommended to make multiple calls to use_args or use_kwargs with a distinct schema per location. For example, code should be rewritten like this:
# webargs 5.x and older
@parser.use_args(
{
"q1": ma.fields.Int(location="query"),
"q2": ma.fields.Int(location="query"),
"h1": ma.fields.Int(location="headers"),
},
locations=("query", "headers"),
)
def foo(q1, q2, h1): ...
# webargs 6.x
@parser.use_args({"q1": ma.fields.Int(), "q2": ma.fields.Int()}, location="query")
@parser.use_args({"h1": ma.fields.Int()}, location="headers")
def foo(q1, q2, h1): ...- The location_handler decorator has been removed and replaced with location_loader. location_loader serves the same purpose (letting you write custom hooks for loading data) but its expected method signature is different. See the docs on location_loader for proper usage.
Thanks :user:`sirosen` for the PR!
Bug fixes:
- :cve:`CVE-2020-7965`: Don't attempt to parse JSON if request's content type is mismatched.
Bug fixes:
- Handle
UnicodeDecodeErrorwhen parsing JSON payloads (:issue:`427`). Thanks :user:`lindycoder` for the catch and patch.
Bug fixes:
- Remove usage of deprecated
Field.failwhen using marshmallow 3.
Support:
Refactoring:
- Don't mutate
globals()inwebargs.fields(:pr:`411`). - Use marshmallow 3's
Schema.from_dictif available (:pr:`415`).
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 (:issue:`406`).
Bug fixes:
- marshmallow 3.0.0rc7 compatibility (:pr:`395`).
Bug fixes:
- marshmallow 3.0.0rc6 compatibility (:pr:`384`).
Features:
- Add "path" location to
AIOHTTPParser,FlaskParser, andPyramidParser(:pr:`379`). Thanks :user:`zhenhua32` for the PR. - Add
webargs.__version_info__.
Features:
- Make the schema class used when generating a schema from a dict overridable (:issue:`375`). Thanks :user:`ThiefMaster`.
Bug fixes:
- :cve:`CVE-2019-9710`: Fix race condition between parallel requests when the cache is used (:issue:`371`). Thanks :user:`ThiefMaster` for reporting and fixing.
Bug fixes:
- Remove lingering usages of
ValidationError.status_code(:issue:`365`). Thanks :user:`decaz` for reporting. - Avoid
AttributeErroron Python<3.5.4 (:issue:`366`). - Fix incorrect type annotations for
error_headers. - Fix outdated docs (:issue:`367`). Thanks :user:`alexandersoto` for reporting.
- Include LICENSE in sdist (:issue:`364`).
Bug fixes:
- Fix installing
simplejsonon Python 2 by distributing a Python 2-only wheel (:issue:`363`).
Features:
- Error handlers for AsyncParser classes may be coroutine functions.
- Add type annotations to AsyncParser and AIOHTTPParser.
Bug fixes:
- Fix compatibility with Flask<1.0 (:issue:`355`). Thanks :user:`hoatle` for reporting.
- Address warning on Python 3.7 about importing from
collections.abc.
Features:
- Backwards-incompatible: A 400 HTTPError is raised when an invalid JSON payload is passed. (:issue:`329`). Thanks :user:`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(:issue:`342,307,252`). Use**kwargsto 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 (:pr:`334`). This ensures consistency of behavior across Python 2 and 3.
Bug fixes:
- Remove usages of
argmap2schemafromfields.Nested,AsyncParser, andPyramidParser.
- Deprecation:
argmap2schemais deprecated in favor ofdict2schema(:pr:`352`).
- Add
force_allparam toPyramidParser.use_args. - Add warning about missing arguments to
AsyncParser.
- Deprecation: Add warning about missing arguments getting added to parsed arguments dictionary (:issue:`342`). This behavior will be removed in version 5.0.0.
Features:
- Add
force_allargument touse_argsanduse_kwargs(:issue:`252`, :issue:`307`). Thanks :user:`piroux` for reporting. - Deprecation: The
status_codeandheadersarguments toValidationErrorare deprecated. Passerror_status_codeanderror_headersto Parser.parse, Parser.use_args, and Parser.use_kwargs instead. (:issue:`327`, :issue:`336`). - Custom error handlers receive
error_status_codeanderror_headersarguments. (:issue:`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:
- Fix bug in
AIOHTTParserthat prevented callinguse_argson the same view function multiple times (:issue:`273`). Thanks to :user:`dnp1` for reporting and :user:`jangelo` for the fix. - Fix compatibility with marshmallow 3.0.0rc1 (:pr:`330`).
Bug fixes:
- Fix serialization behavior of
DelimitedList(:pr:`319`). Thanks :user:`lee3164` for the PR.
Other changes:
- Test against Python 3.7.
Bug fixes:
- Fix bug in
AIOHTTPParserthat caused aJSONDecodeerror when parsing empty payloads (:issue:`229`). Thanks :user:`explosic4` for reporting and thanks user :user:`kochab` for the PR.
Features:
- Add
webargs.testingmodule, which exposesCommonTestCaseto third-party parser libraries (see comments in :pr:`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
schemaargument, 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.asynctowebargs.asyncparserto fix compatibility with Python 3.7 (:issue:`240`). Thanks :user:`Reskov` for the catch and patch.
Other changes:
- Backwards-incompatible: Drop support for Python 3.4 (:pr:`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 (:pr:`244`).
Bug fixes:
- Fix compatibility with marshmallow 3.0.0b12 (:pr:`242`). Thanks :user:`lafrech`.
Bug fixes:
- Respect Parser.DEFAULT_VALIDATION_STATUS when a status_code is not explicitly passed to ValidationError (:issue:`180`). Thanks :user:`foresmac` for finding this.
Support:
- Add "Returning HTTP 400 Responses" section to docs (:issue:`180`).
Changes:
- Backwards-incompatible: Custom error handlers receive the request object as the second
argument. Update any functions decorated with
Parser.error_handlerto 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
instanceandkwargsarguments ofargmap2schema. - Backwards-incompatible: Remove
Parser.loadmethod (Parsernow callsSchema.loaddirectly).
These changes shouldn't affect most users. However, they might break custom parsers calling these methods. (:pr:`222`)
- Drop support for aiohttp<3.0.0.
Features:
- Respect
data_keyfield argument (in marshmallow 3). Thanks :user:`lafrech`.
Changes:
- Drop support for aiohttp<2.0.0.
- Remove use of deprecated Request.has_body attribute in aiohttpparser (:issue:`186`). Thanks :user:`ariddell` for reporting.
Features:
- Add support for marshmallow>=3.0.0b7 (:pr:`188`). Thanks :user:`lafrech`.
Deprecations:
- Support for aiohttp<2.0.0 is deprecated and will be removed in webargs 2.0.0.
Changes:
HTTPExceptionsraised with webargs.flaskparser.abort will always have thedataattribute, even if no additional keywords arguments are passed (:pr:`184`). Thanks :user:`lafrech`.
Support:
- Fix examples in examples/ directory.
Bug fixes:
- Fix behavior of
AIOHTTPParser.use_argswhenas_kwargs=Trueis passed with aSchema(:issue:`179`). Thanks :user:`Itayazolay`.
Features:
AIOHTTPParsersupports class-based views, i.e.aiohttp.web.View(:issue:`177`). Thanks :user:`daniel98321`.
Features:
AIOHTTPParser.use_argsandAIOHTTPParser.use_kwargswork with async def coroutines (:issue:`170`). Thanks :user:`zaro`.
Support:
- Fix Flask error handling docs in "Framework support" section (:issue:`168`). Thanks :user:`nebularazer`.
Bug fixes:
- Fix parsing multiple arguments in
AIOHTTParser(:issue:`165`). Thanks :user:`ariddell` for reporting and thanks :user:`zaro` for reporting.
Bug fixes:
- Fix form parsing in aiohttp>=2.0.0. Thanks :user:`DmitriyS` for the PR.
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 :issue:`146` for
AIOHTTPParser. - Handle invalid types passed to
DelimitedList(:issue:`149`). Thanks :user:`psconnect-dev` for reporting.
Bug fixes:
- Don't add
marshmallow.missingtooriginal_datawhen usingmarshmallow.validates_schema(pass_original=True)(:issue:`146`). Thanks :user:`lafrech` for reporting and for the fix.
Other changes:
- Test against Python 3.6.
Bug fixes:
- Fix handling missing nested args when
many=True(:issue:`120`, :issue:`145`). Thanks :user:`chavz` and :user:`Bangertm` for reporting. - Fix behavior of
load_frominAIOHTTPParser.
Features:
- The
use_argsanduse_kwargsdecorators add a reference to the undecorated function via the__wrapped__attribute. This is useful for unit-testing purposes (:issue:`144`). Thanks :user:`EFF` for the PR.
Bug fixes:
- If
load_fromis specified on a field, first check the field name before checkingload_from(:issue:`118`). Thanks :user:`jasonab` for reporting.
Bug fixes:
- Prevent error when rendering validation errors to JSON in Flask (e.g. when using Flask-RESTful) (:issue:`122`). Thanks :user:`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
ValidationErrorobject.
# 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}), 422Bug fixes:
- Fix bug in parsing form in Falcon>=1.0.
Bug fixes:
- Fix behavior for nullable List fields (:issue:`107`). Thanks :user:`shaicantor` for reporting.
Bug fixes:
- Fix passing a schema factory to
use_kwargs(:issue:`103`). Thanks :user:`ksesong` for reporting.
Bug fixes:
- Fix memory leak when calling
parser.parsewith adictin a view (:issue:`101`). Thanks :user:`frankslaughter` for reporting. - aiohttpparser: Fix bug in handling bulk-type arguments.
Support:
- Massive refactor of tests (:issue:`98`).
- Docs: Fix incorrect use_args example in Tornado section (:issue:`100`). Thanks :user:`frankslaughter` for reporting.
- Docs: Add "Mixing Locations" section (:issue:`90`). Thanks :user:`tuukkamustonen`.
Features:
- Add bulk-type arguments support for JSON parsing by passing
many=Trueto aSchema(:issue:`81`). Thanks :user:`frol`.
Bug fixes:
- Fix JSON parsing in Flask<=0.9.0. Thanks :user:`brettdh` for the PR.
- Fix behavior of
status_codeargument toValidationError(:issue:`85`). This requires marshmallow>=2.7.0. Thanks :user:`ParthGandhi` for reporting.
Support:
- Docs: Add "Custom Fields" section with example of using a
Functionfield (:issue:`94`). Thanks :user:`brettdh` for the suggestion.
Features:
- Add
view_argsrequest location toFlaskParser(:issue:`82`). Thanks :user:`oreza` for the suggestion.
Bug fixes:
- Use the value of
load_fromas the key for error messages when it is provided (:issue:`83`). Thanks :user:`immerrr` for the catch and patch.
Bug fixes:
- aiohttpparser: Fix bug that raised a
JSONDecodeErrorraised when parsing non-JSON requests using defaultlocations(:issue:`80`). Thanks :user:`leonidumanskiy` for reporting. - Fix parsing JSON requests that have a vendor media type, e.g.
application/vnd.api+json.
Features:
Parser.parse,Parser.use_argsandParser.use_kwargscan take a Schema factory as the first argument (:issue:`73`). Thanks :user:`DamianHeard` for the suggestion and the PR.
Support:
- Docs: Add "Custom Parsers" section with example of parsing nested querystring arguments (:issue:`74`). Thanks :user:`dwieeb`.
- Docs: Add "Advanced Usage" page.
Features:
- Add
AIOHTTPParser(:issue:`71`). - Add
webargs.asyncmodule withAsyncParser.
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 (:issue:`70`). Thanks :user:`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_argsgets passed a view function as its first argument. - Backwards-incompatible: Remove logging from default error handlers.
Features:
- Add
FalconParser(:issue:`63`). - Add
fields.DelimitedList(:issue:`66`). Thanks :user:`jmcarp`. TornadoParserwill parse json withsimplejsonif it is installed.BottleParsercaches parsed json per-request for improved performance.
No breaking changes. Yay!
Features:
TornadoParserreturns unicode strings rather than bytestrings (:issue:`41`). Thanks :user:`thomasboyt` for the suggestion.- Add
Parser.get_default_requestandParser.get_request_from_view_argshooks to simplifyParserimplementations. - Backwards-compatible:
webargs.core.get_valuetakes aFieldas its last argument. Note: this is technically a breaking change, but this won't affect most users sinceget_valueis only used internally byParserclasses.
Support:
- Add
examples/annotations_example.py(demonstrates using Python 3 function annotations to define request arguments). - Fix examples. Thanks :user:`hyunchel` for catching an error in the Flask error handling docs.
Bug fixes:
- Correctly pass
validateandforce_allparams toPyramidParser.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(load_default=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" (:issue:`58`).
Changes:
- Backwards-incompatible: Replace
Argswith marshmallow fields (:issue:`61`). - Backwards-incompatible: When using
use_kwargs, missing arguments will have the special valuemissingrather thanNone. TornadoParserraises a customHTTPErrorwith amessagesattribute when validation fails.
Bug fixes:
- Fix required validation of nested arguments (:issue:`39`, :issue:`51`). These are fixed by virtue of using marshmallow's
Nestedfield. Thanks :user:`ewang` and :user:`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 :issue:`54`. Thanks :user:`marcellarius`.
Bug fixes:
- Fix parsing nested
Argswhen the argument is missing from the input (:issue:`52`). Thanks :user:`stas`.
Features:
- Add parsing of
matchdicttoPyramidParser. Thanks :user:`hartror`.
Bug fixes:
- Fix
PyramidParser'suse_kwargsmethod (:issue:`42`). Thanks :user:`hartror` for the catch and patch. - Correctly use locations passed to Parser's constructor when using
use_args(:issue:`44`). Thanks :user:`jacebrowning` for the catch and patch. - Fix behavior of
defaultanddestargument on nestedArgs(:issue:`40` and :issue:`46`). Thanks :user:`stas`.
Changes:
- A 422 response is returned to the client when a
ValidationErroris raised by a parser (:issue:`38`).
Features:
- Support for webapp2 via the webargs.webapp2parser module. Thanks :user:`Trii`.
- Store argument name on
RequiredArgMissingError. Thanks :user:`stas`. - Allow error messages for required validation to be overriden. Thanks again :user:`stas`.
Removals:
- Remove
sourceparameter fromArg.
Features:
- Store argument name on
ValidationError(:issue:`32`). Thanks :user:`alexmic` for the suggestion. Thanks :user:`stas` for the patch. - Allow nesting of dict subtypes.
Changes:
- Add
destparameter toArgconstructor which determines the key to be added to the parsed arguments dictionary (:issue:`32`). - Backwards-incompatible: Rename
targetsparameter tolocationsinParserconstructor,Parser#parse_arg,Parser#parse,Parser#use_args, andParser#use_kwargs. - Backwards-incompatible: Rename
Parser#target_handlertoParser#location_handler.
Deprecation:
- The
sourceparameter is deprecated in favor of thedestparameter.
Bug fixes:
- Fix
validateparameter ofDjangoParser#use_args.
- When parsing a nested
Arg, filter out extra arguments that are not part of theArg'snesteddict(:issue:`28`). Thanks Derrick Gilland for the suggestion. - Fix bug in parsing
Argswith both type coercion andmultiple=True(:issue:`30`). Thanks Steven Manuatu for reporting. - Raise
RequiredArgMissingErrorwhen a required argument is missing on a request.
- Fix behavior of
multiple=Truewhen nesting Args (:issue:`29`). Thanks Derrick Gilland for reporting.
- Pyramid support thanks to @philtay.
- User-friendly error messages when
Argtype conversion/validation fails. Thanks Andriy Yurchuk. - Allow
useargument to be a list of functions. - Allow
Argsto be nested within each other, e.g. for nested dict validation. Thanks @saritasa for the suggestion. - Backwards-incompatible: Parser will only pass
ValidationErrorsto its error handler function, rather than catching all generic Exceptions. - Backwards-incompatible: Rename
Parser.TARGET_MAPtoParser.__target_map__. - Add a short-lived cache to the
Parserclass that can be used to store processed request data for reuse. - Docs: Add example usage with Flask-RESTful.
- Fix bug in
TornadoParserthat raised an error when request body is not a string (e.g when it is aFuture). Thanks Josh Carp.
- Fix
Parser.use_kwargsbehavior when anArgis allowed missing. Theallow_missingattribute is ignored whenuse_kwargsis called. defaultmay be a callable.- Allow
ValidationErrorto 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
ArgorParser.parse. - A more useful
__repr__forArg. - Add examples and updated docs.
- Add
sourceparameter toArgconstructor. Allows renaming of keys in the parsed arguments dictionary. Thanks Josh Carp. FlaskParser'shandle_errormethod attaches the string representation of validation errors onerr.data['message']. The raised exception is stored onerr.data['exc'].- Additional keyword arguments passed to
Argare stored as metadata.
- Fix bug in
TornadoParser'shandle_errormethod. Thanks Josh Carp. - Add
errorparameter toParserconstructor that allows a custom error message to be used if schema-level validation fails. - Fix bug that raised a
UnicodeEncodeErroron Python 2 when an Arg's validator function received non-ASCII input.
- Fix regression with parsing an
Argwith bothdefaultandtargetset (see issue #11).
- Add
validateparameter toParser.parseandParser.use_args. Allows validation of the full parsed output. - If
allow_missingisTrueon anArgfor whichNoneis explicitly passed, the value will still be present in the parsed arguments dictionary. - Backwards-incompatible:
Parser'sparse_*methods returnwebargs.core.Missingif the value cannot be found on the request. NOTE:webargs.core.Missingwill not show up in the final output ofParser.parse. - Fix bug with parsing empty request bodies with
TornadoParser.
- Fix behavior of
Arg'sallow_missingparameter whenmultiple=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
useparameter toArgis 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_handlerdecorator. - Error handler can be specified using the
Parser.error_handlerdecorator. Argscan define their request target by passing in atargetargument.- Backwards-incompatible:
DEFAULT_TARGETSis now a class member ofParser. This allows subclasses to override it.
- Fix bug that caused
use_argsto fail on class-based views in Flask. - Add
allow_missingparameter toArg.
- Awesome contributions from the open-source community!
- Add
use_kwargsdecorator. 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_handlerparam toParser.
- Bottle support.
- Add
targetsparam toParser. Allows setting default targets. - Add
filestarget.
- First release.
- Parses JSON, querystring, forms, headers, and cookies.
- Support for Flask and Django.