Release v5.5.3. (Changelog)
webargs is a Python library for parsing and validating HTTP request objects, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp.
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
@app.route("/")
@use_args({"name": fields.Str(required=True)})
def index(args):
return "Hello " + args["name"]
if __name__ == "__main__":
app.run()
# curl http://localhost:5000/\?name\='World'
# Hello World
Webargs will automatically parse:
Query Parameters
$ curl http://localhost:5000/\?name\='Freddie'
Hello Freddie
Form Data
$ curl -d 'name=Brian' http://localhost:5000/
Hello Brian
JSON Data
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"Roger"}' http://localhost:5000/
Hello Roger
and, optionally:
Headers
Cookies
Files
Paths
Simple, declarative syntax. Define your arguments as a mapping rather than imperatively pulling values off of request objects.
Code reusability. If you have multiple views that have the same request parameters, you only need to define your parameters once. You can also reuse validation and pre-processing routines.
Self-documentation. Webargs makes it easy to understand the expected arguments and their types for your view functions.
Automatic documentation. The metadata that webargs provides can serve as an aid for automatically generating API documentation.
Cross-framework compatibility. Webargs provides a consistent request-parsing interface that will work across many Python web frameworks.
marshmallow integration. Webargs uses marshmallow under the hood. When you need more flexibility than dictionaries, you can use marshmallow Schemas
to define your request arguments.
pip install -U webargs
Ready to get started? Go on to the Quickstart tutorial or check out some examples.
webargs requires Python >= 2.7 or >= 3.5. It depends on marshmallow >= 2.7.0.
To get the latest development version of webargs, run
$ pip install -U git+https://github.com/marshmallow-code/webargs.git@dev
Arguments are specified as a dictionary of name -> Field
pairs.
from webargs import fields, validate
user_args = {
# Required arguments
"username": fields.Str(required=True),
# Validation
"password": fields.Str(validate=lambda p: len(p) >= 6),
# OR use marshmallow's built-in validators
"password": fields.Str(validate=validate.Length(min=6)),
# Default value when argument is missing
"display_per_page": fields.Int(missing=10),
# Repeated parameter, e.g. "/?nickname=Fred&nickname=Freddie"
"nickname": fields.List(fields.Str()),
# Delimited list, e.g. "/?languages=python,javascript"
"languages": fields.DelimitedList(fields.Str()),
# When you know where an argument should be parsed from
"active": fields.Bool(location="query"),
# When value is keyed on a variable-unsafe name
# or you want to rename a key
"content_type": fields.Str(load_from="Content-Type", location="headers"),
# OR, on marshmallow 3
# "content_type": fields.Str(data_key="Content-Type", location="headers"),
# File uploads
"profile_image": fields.Field(
location="files", validate=lambda f: f.mimetype in ["image/jpeg", "image/png"]
),
}
Note
See the marshmallow.fields
documentation for a full reference on available field types.
To parse request arguments, use the parse
method of a Parser
object.
from flask import request
from webargs.flaskparser import parser
@app.route("/register", methods=["POST"])
def register():
args = parser.parse(user_args, request)
return register_user(
args["username"],
args["password"],
fullname=args["fullname"],
per_page=args["display_per_page"],
)
As an alternative to Parser.parse
, you can decorate your view with use_args
or use_kwargs
. The parsed arguments dictionary will be injected as a parameter of your view function or as keyword arguments, respectively.
from webargs.flaskparser import use_args, use_kwargs
@app.route("/register", methods=["POST"])
@use_args(user_args) # Injects args dictionary
def register(args):
return register_user(
args["username"],
args["password"],
fullname=args["fullname"],
per_page=args["display_per_page"],
)
@app.route("/settings", methods=["POST"])
@use_kwargs(user_args) # Injects keyword arguments
def user_settings(username, password, fullname, display_per_page, nickname):
return render_template("settings.html", username=username, nickname=nickname)
Note
When using use_kwargs
, any missing values will be omitted from the arguments.
Use **kwargs
to handle optional arguments.
from webargs import fields, missing
@use_kwargs({"name": fields.Str(required=True), "nickname": fields.Str(required=False)})
def myview(name, **kwargs):
if "nickname" not in kwargs:
# ...
pass
By default, webargs will search for arguments from the URL query string (e.g. "/?name=foo"
), form data, and JSON data (in that order). You can explicitly specify which locations to search, like so:
@app.route("/register")
@use_args(user_args, locations=("json", "form"))
def register(args):
return "registration page"
Available locations include:
'querystring'
(same as 'query'
)
'json'
'form'
'headers'
'cookies'
'files'
Each Field
object can be validated individually by passing the validate
argument.
from webargs import fields
args = {"age": fields.Int(validate=lambda val: val > 0)}
The validator may return either a boolean
or raise a ValidationError
.
from webargs import fields, ValidationError
def must_exist_in_db(val):
if not User.query.get(val):
# Optionally pass a status_code
raise ValidationError("User does not exist")
args = {"id": fields.Int(validate=must_exist_in_db)}
Note
If a validator returns None
, validation will pass. A validator must return False
or raise a ValidationError
for validation to fail.
There are a number of built-in validators from marshmallow.validate
(re-exported as webargs.validate
).
from webargs import fields, validate
args = {
"name": fields.Str(required=True, validate=[validate.Length(min=1, max=9999)]),
"age": fields.Int(validate=[validate.Range(min=1, max=999)]),
}
The full arguments dictionary can also be validated by passing validate
to Parser.parse
, Parser.use_args
, Parser.use_kwargs
.
from webargs import fields
from webargs.flaskparser import parser
argmap = {"age": fields.Int(), "years_employed": fields.Int()}
# ...
result = parser.parse(
argmap, validate=lambda args: args["years_employed"] < args["age"]
)
Each parser has a default error handling method. To override the error handling callback, write a function that
receives an error, the request, the marshmallow.Schema
instance, status code, and headers.
Then decorate that function with Parser.error_handler
.
from webargs import flaskparser
parser = flaskparser.FlaskParser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
Use fields.DelimitedList
to parse comma-separated
lists in query parameters, e.g. /?permissions=read,write
from webargs import fields
args = {"permissions": fields.DelimitedList(fields.Str())}
If you expect repeated query parameters, e.g. /?repo=webargs&repo=marshmallow
, use
fields.List
instead.
from webargs import fields
args = {"repo": fields.List(fields.Str())}
Field
dictionaries can be nested within each other. This can be useful for validating nested data.
from webargs import fields
args = {
"name": fields.Nested(
{"first": fields.Str(required=True), "last": fields.Str(required=True)}
)
}
Note
By default, webargs only parses nested fields using the json
request location. You can, however, implement your own parser to add nested field functionality to the other locations.
Go on to Advanced Usage to learn how to add custom location handlers, use marshmallow Schemas, and more.
See the Framework Support page for framework-specific guides.
For example applications, check out the examples directory.
This section includes guides for advanced usage patterns.
To add your own custom location handler, write a function that receives a request, an argument name, and a Field
, then decorate that function with Parser.location_handler
.
from webargs import fields
from webargs.flaskparser import parser
@parser.location_handler("data")
def parse_data(request, name, field):
return request.data.get(name)
# Now 'data' can be specified as a location
@parser.use_args({"per_page": fields.Int()}, locations=("data",))
def posts(args):
return "displaying {} posts".format(args["per_page"])
When you need more flexibility in defining input schemas, you can pass a marshmallow Schema
instead of a dictionary to Parser.parse
, Parser.use_args
, and Parser.use_kwargs
.
from marshmallow import Schema, fields
from webargs.flaskparser import use_args
class UserSchema(Schema):
id = fields.Int(dump_only=True) # read-only (won't be parsed by webargs)
username = fields.Str(required=True)
password = fields.Str(load_only=True) # write-only
first_name = fields.Str(missing="")
last_name = fields.Str(missing="")
date_registered = fields.DateTime(dump_only=True)
# NOTE: Uncomment below two lines if you're using marshmallow 2
# class Meta:
# strict = True
@use_args(UserSchema())
def profile_view(args):
username = args["userame"]
# ...
@use_kwargs(UserSchema())
def profile_update(username, password, first_name, last_name):
update_profile(username, password, first_name, last_name)
# ...
# You can add additional parameters
@use_kwargs({"posts_per_page": fields.Int(missing=10, location="query")})
@use_args(UserSchema())
def profile_posts(args, posts_per_page):
username = args["username"]
# ...
Warning
If you’re using marshmallow 2, you should always set strict=True
(either as a class Meta
option or in the Schema’s constructor) when passing a schema to webargs. This will ensure that the parser’s error handler is invoked when expected.
Warning
Any Schema
passed to use_kwargs
MUST deserialize to a dictionary of data. Keep this in mind when writing post_load
methods.
If you need to parametrize a schema based on a given request, you can use a “Schema factory”: a callable that receives the current request
and returns a marshmallow.Schema
instance.
Consider the following use cases:
Filtering via a query parameter by passing only
to the Schema.
Handle partial updates for PATCH requests using marshmallow’s partial loading API.
from flask import Flask
from marshmallow import Schema, fields
from webargs.flaskparser import use_args
app = Flask(__name__)
class UserSchema(Schema):
id = fields.Int(dump_only=True)
username = fields.Str(required=True)
password = fields.Str(load_only=True)
first_name = fields.Str(missing="")
last_name = fields.Str(missing="")
date_registered = fields.DateTime(dump_only=True)
def make_user_schema(request):
# Filter based on 'fields' query parameter
fields = request.args.get("fields", None)
only = fields.split(",") if fields else None
# Respect partial updates for PATCH requests
partial = request.method == "PATCH"
# Add current request to the schema's context
return UserSchema(only=only, partial=partial, context={"request": request})
# Pass the factory to .parse, .use_args, or .use_kwargs
@app.route("/profile/", methods=["GET", "POST", "PATCH"])
@use_args(make_user_schema)
def profile_view(args):
username = args.get("username")
# ...
We can reduce boilerplate and improve [re]usability with a simple helper function:
from webargs.flaskparser import use_args
def use_args_with(schema_cls, schema_kwargs=None, **kwargs):
schema_kwargs = schema_kwargs or {}
def factory(request):
# Filter based on 'fields' query parameter
only = request.args.get("fields", None)
# Respect partial updates for PATCH requests
partial = request.method == "PATCH"
return schema_cls(
only=only, partial=partial, context={"request": request}, **schema_kwargs
)
return use_args(factory, **kwargs)
Now we can attach input schemas to our view functions like so:
@use_args_with(UserSchema)
def profile_view(args):
# ...
get_profile(**args)
See the “Custom Fields” section of the marshmallow docs for a detailed guide on defining custom fields which you can pass to webargs parsers: https://marshmallow.readthedocs.io/en/latest/custom_fields.html.
To add your own parser, extend Parser
and implement the parse_*
method(s) you need to override. For example, here is a custom Flask parser that handles nested query string arguments.
import re
from webargs import core
from webargs.flaskparser import FlaskParser
class NestedQueryFlaskParser(FlaskParser):
"""Parses nested query args
This parser handles nested query args. It expects nested levels
delimited by a period and then deserializes the query args into a
nested dict.
For example, the URL query params `?name.first=John&name.last=Boone`
will yield the following dict:
{
'name': {
'first': 'John',
'last': 'Boone',
}
}
"""
def parse_querystring(self, req, name, field):
return core.get_value(_structure_dict(req.args), name, field)
def _structure_dict(dict_):
def structure_dict_pair(r, key, value):
m = re.match(r"(\w+)\.(.*)", key)
if m:
if r.get(m.group(1)) is None:
r[m.group(1)] = {}
structure_dict_pair(r[m.group(1)], m.group(2), value)
else:
r[key] = value
r = {}
for k, v in dict_.items():
structure_dict_pair(r, k, v)
return r
If you’d prefer validation errors to return status code 400
instead
of 422
, you can override DEFAULT_VALIDATION_STATUS
on a Parser
.
from webargs.falconparser import FalconParser
class Parser(FalconParser):
DEFAULT_VALIDATION_STATUS = 400
parser = Parser()
use_args = parser.use_args
use_kwargs = parser.use_kwargs
In order to parse a JSON array of objects, pass many=True
to your input Schema
.
For example, you might implement JSON PATCH according to RFC 6902 like so:
from webargs import fields
from webargs.flaskparser import use_args
from marshmallow import Schema, validate
class PatchSchema(Schema):
op = fields.Str(
required=True,
validate=validate.OneOf(["add", "remove", "replace", "move", "copy"]),
)
path = fields.Str(required=True)
value = fields.Str(required=True)
@app.route("/profile/", methods=["patch"])
@use_args(PatchSchema(many=True), locations=("json",))
def patch_blog(args):
"""Implements JSON Patch for the user profile
Example JSON body:
[
{"op": "replace", "path": "/email", "value": "mynewemail@test.org"}
]
"""
# ...
Arguments for different locations can be specified by passing location
to each field individually:
@app.route("/stacked", methods=["POST"])
@use_args(
{
"page": fields.Int(location="query"),
"q": fields.Str(location="query"),
"name": fields.Str(location="json"),
}
)
def viewfunc(args):
page = args["page"]
# ...
Alternatively, you can pass multiple locations to use_args
:
@app.route("/stacked", methods=["POST"])
@use_args(
{"page": fields.Int(), "q": fields.Str(), "name": fields.Str()},
locations=("query", "json"),
)
def viewfunc(args):
page = args["page"]
# ...
However, this allows page
and q
to be passed in the request body and name
to be passed as a query parameter.
To restrict the arguments to single locations without having to pass location
to every field, you can call the use_args
multiple times:
query_args = {"page": fields.Int(), "q": fields.Int()}
json_args = {"name": fields.Str()}
@app.route("/stacked", methods=["POST"])
@use_args(query_args, locations=("query",))
@use_args(json_args, locations=("json",))
def viewfunc(query_parsed, json_parsed):
page = query_parsed["page"]
name = json_parsed["name"]
# ...
To reduce boilerplate, you could create shortcuts, like so:
import functools
query = functools.partial(use_args, locations=("query",))
body = functools.partial(use_args, locations=("json",))
@query(query_args)
@body(json_args)
def viewfunc(query_parsed, json_parsed):
page = query_parsed["page"]
name = json_parsed["name"]
# ...
See the Framework Support page for framework-specific guides.
For example applications, check out the examples directory.
This section includes notes for using webargs with specific web frameworks.
Flask support is available via the webargs.flaskparser
module.
When using the use_args
decorator, the arguments dictionary will be before any URL variable parameters.
from webargs import fields
from webargs.flaskparser import use_args
@app.route("/user/<int:uid>")
@use_args({"per_page": fields.Int()})
def user_detail(args, uid):
return ("The user page for user {uid}, " "showing {per_page} posts.").format(
uid=uid, per_page=args["per_page"]
)
Webargs uses Flask’s abort
function to raise an HTTPException
when a validation error occurs.
If you use the Flask.errorhandler
method to handle errors, you can access validation messages from the messages
attribute of
the attached ValidationError
.
Here is an example error handler that returns validation messages to the client as JSON.
from flask import jsonify
# Return validation errors as JSON
@app.errorhandler(422)
@app.errorhandler(400)
def handle_error(err):
headers = err.data.get("headers", None)
messages = err.data.get("messages", ["Invalid request."])
if headers:
return jsonify({"errors": messages}), err.code, headers
else:
return jsonify({"errors": messages}), err.code
The FlaskParser
supports parsing values from a request’s view_args
.
from webargs.flaskparser import use_args
@app.route("/greeting/<name>/")
@use_args({"name": fields.Str(location="view_args")})
def greeting(args, **kwargs):
return "Hello {}".format(args["name"])
Django support is available via the webargs.djangoparser
module.
Webargs can parse Django request arguments in both function-based and class-based views.
When using the use_args
decorator, the arguments dictionary will positioned after the request
argument.
Function-based Views
from django.http import HttpResponse
from webargs import Arg
from webargs.djangoparser import use_args
account_args = {
"username": fields.Str(required=True),
"password": fields.Str(required=True),
}
@use_args(account_args)
def login_user(request, args):
if request.method == "POST":
login(args["username"], args["password"])
return HttpResponse("Login page")
Class-based Views
from django.views.generic import View
from django.shortcuts import render_to_response
from webargs import fields
from webargs.djangoparser import use_args
blog_args = {"title": fields.Str(), "author": fields.Str()}
class BlogPostView(View):
@use_args(blog_args)
def get(self, request, args):
blog_post = Post.objects.get(title__iexact=args["title"], author=args["author"])
return render_to_response("post_template.html", {"post": blog_post})
The DjangoParser
does not override handle_error
, so your Django views are responsible for catching any ValidationErrors
raised by the parser and returning the appropriate HTTPResponse
.
from django.http import JsonResponse
from webargs import fields, ValidationError, json
argmap = {"name": fields.Str(required=True)}
def index(request):
try:
args = parser.parse(argmap, request)
except ValidationError as err:
return JsonResponse(err.messages, status=422)
except json.JSONDecodeError:
return JsonResponse({"json": ["Invalid JSON body."]}, status=400)
return JsonResponse({"message": "Hello {name}".format(name=name)})
Tornado argument parsing is available via the webargs.tornadoparser
module.
The webargs.tornadoparser.TornadoParser
parses arguments from a tornado.httpserver.HTTPRequest
object. The TornadoParser
can be used directly, or you can decorate handler methods with use_args
or use_kwargs
.
import tornado.ioloop
import tornado.web
from webargs import fields
from webargs.tornadoparser import parser
class HelloHandler(tornado.web.RequestHandler):
hello_args = {"name": fields.Str()}
def post(self, id):
reqargs = parser.parse(self.hello_args, self.request)
response = {"message": "Hello {}".format(reqargs["name"])}
self.write(response)
application = tornado.web.Application([(r"/hello/([0-9]+)", HelloHandler)], debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
When using the use_args
decorator, the decorated method will have the dictionary of parsed arguments passed as a positional argument after self
and any regex match groups from the URL spec.
from webargs import fields
from webargs.tornadoparser import use_args
class HelloHandler(tornado.web.RequestHandler):
@use_args({"name": fields.Str()})
def post(self, id, reqargs):
response = {"message": "Hello {}".format(reqargs["name"])}
self.write(response)
application = tornado.web.Application([(r"/hello/([0-9]+)", HelloHandler)], debug=True)
As with the other parser modules, use_kwargs
will add keyword arguments to the view callable.
A HTTPError
will be raised in the event of a validation error. Your RequestHandlers
are responsible for handling these errors.
Here is how you could write the error messages to a JSON response.
from tornado.web import RequestHandler
class MyRequestHandler(RequestHandler):
def write_error(self, status_code, **kwargs):
"""Write errors as JSON."""
self.set_header("Content-Type", "application/json")
if "exc_info" in kwargs:
etype, exc, traceback = kwargs["exc_info"]
if hasattr(exc, "messages"):
self.write({"errors": exc.messages})
if getattr(exc, "headers", None):
for name, val in exc.headers.items():
self.set_header(name, val)
self.finish()
Pyramid support is available via the webargs.pyramidparser
module.
When using the use_args
decorator on a view callable, the arguments dictionary will be positioned after the request
argument.
from pyramid.response import Response
from webargs import fields
from webargs.pyramidparser import use_args
@use_args({"uid": fields.Str(), "per_page": fields.Int()})
def user_detail(request, args):
uid = args["uid"]
return Response(
"The user page for user {uid}, showing {per_page} posts.".format(
uid=uid, per_page=args["per_page"]
)
)
As with the other parser modules, use_kwargs
will add keyword arguments to the view callable.
The PyramidParser
supports parsing values from a request’s matchdict.
from pyramid.response import Response
from webargs.pyramidparser import use_args
@use_args({"mymatch": fields.Int()}, locations=("matchdict",))
def matched(request, args):
return Response("The value for mymatch is {}".format(args["mymatch"]))
Falcon support is available via the webargs.falconparser
module.
When using the use_args
decorator on a resource method, the arguments dictionary will be positioned directly after the request and response arguments.
import falcon
from webargs import fields
from webargs.falconparser import use_args
class BlogResource:
request_args = {"title": fields.Str(required=True)}
@use_args(request_args)
def on_post(self, req, resp, args, post_id):
content = args["title"]
# ...
api = application = falcon.API()
api.add_route("/blogs/{post_id}")
As with the other parser modules, use_kwargs
will add keyword arguments to your resource methods.
You can easily implement hooks by using parser.parse
directly.
import falcon
from webargs import fields
from webargs.falconparser import parser
def add_args(argmap, **kwargs):
def hook(req, resp, params):
parsed_args = parser.parse(argmap, req=req, **kwargs)
req.context["args"] = parsed_args
return hook
@falcon.before(add_args({"page": fields.Int(location="query")}))
class AuthorResource:
def on_get(self, req, resp):
args = req.context["args"]
page = args.get("page")
# ...
aiohttp support is available via the webargs.aiohttpparser
module.
The parse
method of AIOHTTPParser
is a coroutine
.
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import parser
handler_args = {"name": fields.Str(missing="World")}
async def handler(request):
args = await parser.parse(handler_args, request)
return web.Response(body="Hello, {}".format(args["name"]).encode("utf-8"))
When using the use_args
decorator on a handler, the parsed arguments dictionary will be the last positional argument.
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_args
@use_args({"content": fields.Str(required=True)})
async def create_comment(request, args):
content = args["content"]
# ...
app = web.Application()
app.router.add_route("POST", "/comments/", create_comment)
As with the other parser modules, use_kwargs
will add keyword arguments to your resource methods.
The use_args
and use_kwargs
decorators will work with both async def
coroutines and generator-based coroutines decorated with asyncio.coroutine
.
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_kwargs
hello_args = {"name": fields.Str(missing="World")}
# The following are equivalent
@asyncio.coroutine
@use_kwargs(hello_args)
def hello(request, name):
return web.Response(body="Hello, {}".format(name).encode("utf-8"))
@use_kwargs(hello_args)
async def hello(request, name):
return web.Response(body="Hello, {}".format(name).encode("utf-8"))
The AIOHTTPParser
supports parsing values from a request’s match_info
.
from aiohttp import web
from webargs.aiohttpparser import use_args
@parser.use_args({"slug": fields.Str(location="match_info")})
def article_detail(request, args):
return web.Response(body="Slug: {}".format(args["slug"]).encode("utf-8"))
app = web.Application()
app.router.add_route("GET", "/articles/{slug}", article_detail)
Bottle support is available via the webargs.bottleparser
module.
The preferred way to apply decorators to Bottle routes is using the
apply
argument.
from bottle import route
user_args = {"name": fields.Str(missing="Friend")}
@route("/users/<_id:int>", method="GET", apply=use_args(user_args))
def users(args, _id):
"""A welcome page.
"""
return {"message": "Welcome, {}!".format(args["name"]), "_id": _id}
A list of webargs-related libraries can be found at the GitHub wiki here:
webargs.core.
ValidationError
(message: Union[str, List, Dict], field_name: str = '_schema', data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]] = None, valid_data: Union[List[Dict[str, Any]], Dict[str, Any]] = None, **kwargs)[source]¶Raised when validation fails on a field or schema.
Validators and custom fields should raise this exception.
message – An error message, list of error messages, or dict of error messages. If a dict, the keys are subitems and the values are error messages.
field_name – Field name to store the error on.
If None
, the error is stored as schema-level error.
data – Raw input data.
valid_data – Valid (de)serialized data.
with_traceback
()¶Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
webargs.core.
dict2schema
(dct, schema_class=<class 'marshmallow.schema.Schema'>)[source]¶Generate a marshmallow.Schema
class given a dictionary of
Fields
.
webargs.core.
is_multiple
(field)[source]¶Return whether or not field
handles repeated/multi-value arguments.
webargs.core.
Parser
(locations=None, error_handler=None, schema_class=None)[source]¶Base parser class that provides high-level implementation for parsing a request.
Descendant classes must provide lower-level implementations for parsing
different locations, e.g. parse_json
, parse_querystring
, etc.
locations (tuple) – Default locations to parse.
error_handler (callable) – Custom error handler function.
DEFAULT_LOCATIONS
= ('querystring', 'form', 'json')¶Default locations to check for data
DEFAULT_SCHEMA_CLASS
¶alias of marshmallow.schema.Schema
DEFAULT_VALIDATION_MESSAGE
= 'Invalid value.'¶Default error message for validation errors
DEFAULT_VALIDATION_STATUS
= 422¶Default status code to return for validation errors
clear_cache
()[source]¶Invalidate the parser’s cache.
This is usually a no-op now since the Parser clone used for parsing a
request is discarded afterwards. It can still be used when manually
calling parse_*
methods which would populate the cache on the main
Parser instance.
error_handler
(func)[source]¶Decorator that registers a custom error handling function. The
function should receive the raised error, request object,
marshmallow.Schema
instance used to parse the request, error status code,
and headers to use for the error response. Overrides
the parser’s handle_error
method.
Example:
from webargs import flaskparser
parser = flaskparser.FlaskParser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
func (callable) – The error callback to register.
get_default_request
()[source]¶Optional override. Provides a hook for frameworks that use thread-local request objects.
get_request_from_view_args
(view, args, kwargs)[source]¶Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the use_args
and use_kwargs
to get a request object from a
view’s arguments.
view (callable) – The view function or method being decorated by
use_args
or use_kwargs
args (tuple) – Positional arguments passed to view
.
kwargs (dict) – Keyword arguments passed to view
.
handle_error
(error, req, schema, error_status_code=None, error_headers=None)[source]¶Called if an error occurs while parsing args. By default, just logs and
raises error
.
location_handler
(name)[source]¶Decorator that registers a function for parsing a request location.
The wrapped function receives a request, the name of the argument, and
the corresponding Field
object.
Example:
from webargs import core
parser = core.Parser()
@parser.location_handler("name")
def parse_data(request, name, field):
return request.data.get(name)
name (str) – The name of the location to register.
parse
(argmap, req=None, locations=None, validate=None, error_status_code=None, error_headers=None)[source]¶Main request parsing method.
argmap – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse.
locations (tuple) – Where on the request to search for values.
Can include one or more of ('json', 'querystring', 'form',
'headers', 'cookies', 'files')
.
validate (callable) – Validation function or list of validation functions
that receives the dictionary of parsed arguments. Validator either returns a
boolean or raises a ValidationError
.
error_status_code (int) – Status code passed to error handler functions when
a ValidationError
is raised.
error_headers (dict) –
a ValidationError
is raised.
A dictionary of parsed arguments
parse_arg
(name, field, req, locations=None)[source]¶Parse a single argument from a request.
Note
This method does not perform validation on the argument.
name (str) – The name of the value.
field (marshmallow.fields.Field) – The marshmallow Field
for the request
parameter.
req – The request object to parse.
locations (tuple) – The locations (‘json’, ‘querystring’, etc.) where to search for the value.
The unvalidated argument value or missing
if the value cannot
be found on the request.
Pull a cookie value from the request or return missing
if the value
cannot be found.
parse_files
(req, name, arg)[source]¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, arg)[source]¶Pull a value from the form data of a request object or return
missing
if the value cannot be found.
parse_headers
(req, name, arg)[source]¶Pull a value from the headers or return missing
if the value
cannot be found.
parse_json
(req, name, arg)[source]¶Pull a JSON value from a request object or return missing
if the
value cannot be found.
parse_querystring
(req, name, arg)[source]¶Pull a value from the query string of a request object or return missing
if
the value cannot be found.
use_args
(argmap, req=None, locations=None, as_kwargs=False, validate=None, error_status_code=None, error_headers=None)[source]¶Decorator that injects parsed arguments into a view function or method.
Example usage with Flask:
@app.route('/echo', methods=['get', 'post'])
@parser.use_args({'name': fields.Str()})
def greet(args):
return 'Hello ' + args['name']
argmap – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
error_status_code (int) – Status code passed to error handler functions when
a ValidationError
is raised.
error_headers (dict) – Headers passed to error handler functions when a
a ValidationError
is raised.
use_kwargs
(*args, **kwargs)[source]¶Decorator that injects parsed arguments into a view function or method as keyword arguments.
This is a shortcut to use_args()
with as_kwargs=True
.
Example usage with Flask:
@app.route('/echo', methods=['get', 'post'])
@parser.use_kwargs({'name': fields.Str()})
def greet(name):
return 'Hello ' + name
Receives the same args
and kwargs
as use_args()
.
Field classes.
Includes all fields from marshmallow.fields
in addition to a custom
Nested
field and DelimitedList
.
All fields can optionally take a special location
keyword argument, which
tells webargs where to parse the request argument from.
args = {
"active": fields.Bool(location='query'),
"content_type": fields.Str(data_key="Content-Type", location="headers"),
}
Note: data_key
replaced load_from
in marshmallow 3.
When using marshmallow 2, use load_from
.
webargs.fields.
Nested
(nested, *args, **kwargs)[source]¶Same as marshmallow.fields.Nested
, except can be passed a dictionary as
the first argument, which will be converted to a marshmallow.Schema
.
Note
The schema class here will always be marshmallow.Schema
, regardless
of whether a custom schema class is set on the parser. Pass an explicit schema
class if necessary.
webargs.fields.
DelimitedList
(cls_or_instance, delimiter=None, as_string=False, **kwargs)[source]¶Same as marshmallow.fields.List
, except can load from either a list or
a delimited string (e.g. “foo,bar,baz”).
Asynchronous request parser. Compatible with Python>=3.5.
webargs.asyncparser.
AsyncParser
(locations=None, error_handler=None, schema_class=None)[source]¶Asynchronous variant of webargs.core.Parser
, where parsing methods may be
either coroutines or regular methods.
DEFAULT_SCHEMA_CLASS
¶alias of marshmallow.schema.Schema
clear_cache
()¶Invalidate the parser’s cache.
This is usually a no-op now since the Parser clone used for parsing a
request is discarded afterwards. It can still be used when manually
calling parse_*
methods which would populate the cache on the main
Parser instance.
error_handler
(func)¶Decorator that registers a custom error handling function. The
function should receive the raised error, request object,
marshmallow.Schema
instance used to parse the request, error status code,
and headers to use for the error response. Overrides
the parser’s handle_error
method.
Example:
from webargs import flaskparser
parser = flaskparser.FlaskParser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
func (callable) – The error callback to register.
get_default_request
()¶Optional override. Provides a hook for frameworks that use thread-local request objects.
get_request_from_view_args
(view, args, kwargs)¶Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the use_args
and use_kwargs
to get a request object from a
view’s arguments.
view (callable) – The view function or method being decorated by
use_args
or use_kwargs
args (tuple) – Positional arguments passed to view
.
kwargs (dict) – Keyword arguments passed to view
.
handle_error
(error, req, schema, error_status_code=None, error_headers=None)¶Called if an error occurs while parsing args. By default, just logs and
raises error
.
location_handler
(name)¶Decorator that registers a function for parsing a request location.
The wrapped function receives a request, the name of the argument, and
the corresponding Field
object.
Example:
from webargs import core
parser = core.Parser()
@parser.location_handler("name")
def parse_data(request, name, field):
return request.data.get(name)
name (str) – The name of the location to register.
parse
(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field]], req: Request = None, locations: Iterable = None, validate: Union[Callable, Iterable[Callable]] = None, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = None) → Optional[Mapping][source]¶Coroutine variant of webargs.core.Parser
.
Receives the same arguments as webargs.core.Parser.parse
.
parse_arg
(name: str, field: marshmallow.fields.Field, req: Request, locations: Iterable = None) → Any[source]¶Parse a single argument from a request.
Note
This method does not perform validation on the argument.
name (str) – The name of the value.
field (marshmallow.fields.Field) – The marshmallow Field
for the request
parameter.
req – The request object to parse.
locations (tuple) – The locations (‘json’, ‘querystring’, etc.) where to search for the value.
The unvalidated argument value or missing
if the value cannot
be found on the request.
Pull a cookie value from the request or return missing
if the value
cannot be found.
parse_files
(req, name, arg)¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, arg)¶Pull a value from the form data of a request object or return
missing
if the value cannot be found.
parse_headers
(req, name, arg)¶Pull a value from the headers or return missing
if the value
cannot be found.
parse_json
(req, name, arg)¶Pull a JSON value from a request object or return missing
if the
value cannot be found.
parse_querystring
(req, name, arg)¶Pull a value from the query string of a request object or return missing
if
the value cannot be found.
use_args
(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field]], req: Optional[Request] = None, locations: Iterable = None, as_kwargs: bool = False, validate: Union[Callable, Iterable[Callable]] = None, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = None) → Callable[[...], Callable][source]¶Decorator that injects parsed arguments into a view function or method.
Receives the same arguments as webargs.core.Parser.use_args
.
use_kwargs
(*args, **kwargs) → Callable[source]¶Decorator that injects parsed arguments into a view function or method.
Receives the same arguments as webargs.core.Parser.use_kwargs
.
Flask request argument parsing module.
Example:
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
hello_args = {
'name': fields.Str(required=True)
}
@app.route('/')
@use_args(hello_args)
def index(args):
return 'Hello ' + args['name']
webargs.flaskparser.
FlaskParser
(locations=None, error_handler=None, schema_class=None)[source]¶Flask request argument parser.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error.
Pull a value from the cookiejar.
Django request argument parsing.
Example usage:
from django.views.generic import View
from django.http import HttpResponse
from marshmallow import fields
from webargs.djangoparser import use_args
hello_args = {
'name': fields.Str(missing='World')
}
class MyView(View):
@use_args(hello_args)
def get(self, args, request):
return HttpResponse('Hello ' + args['name'])
webargs.djangoparser.
DjangoParser
(locations=None, error_handler=None, schema_class=None)[source]¶Django request argument parser.
Warning
DjangoParser
does not override
handle_error
, so your Django
views are responsible for catching any ValidationErrors
raised by
the parser and returning the appropriate HTTPResponse
.
get_request_from_view_args
(view, args, kwargs)[source]¶Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the use_args
and use_kwargs
to get a request object from a
view’s arguments.
Pull the value from the cookiejar.
Bottle request argument parsing module.
Example:
from bottle import route, run
from marshmallow import fields
from webargs.bottleparser import use_args
hello_args = {
'name': fields.Str(missing='World')
}
@route('/', method='GET', apply=use_args(hello_args))
def index(args):
return 'Hello ' + args['name']
if __name__ == '__main__':
run(debug=True)
webargs.bottleparser.
BottleParser
(locations=None, error_handler=None, schema_class=None)[source]¶Bottle.py request argument parser.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Aborts the current request with a 400 error.
Pull a value from the cookiejar.
Tornado request argument parsing module.
Example:
import tornado.web
from marshmallow import fields
from webargs.tornadoparser import use_args
class HelloHandler(tornado.web.RequestHandler):
@use_args({'name': fields.Str(missing='World')})
def get(self, args):
response = {'message': 'Hello {}'.format(args['name'])}
self.write(response)
webargs.tornadoparser.
HTTPError
(*args, **kwargs)[source]¶tornado.web.HTTPError
that stores validation errors.
webargs.tornadoparser.
TornadoParser
(locations=None, error_handler=None, schema_class=None)[source]¶Tornado request argument parser.
get_request_from_view_args
(view, args, kwargs)[source]¶Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the use_args
and use_kwargs
to get a request object from a
view’s arguments.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Raises a tornado.web.HTTPError
with a 400 error.
Pull a value from the header data.
webargs.tornadoparser.
decode_argument
(value, name=None)[source]¶Decodes an argument from the request.
Pyramid request argument parsing.
Example usage:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from marshmallow import fields
from webargs.pyramidparser import use_args
hello_args = {
'name': fields.Str(missing='World')
}
@use_args(hello_args)
def hello_world(request, args):
return Response('Hello ' + args['name'])
if __name__ == '__main__':
config = Configurator()
config.add_route('hello', '/')
config.add_view(hello_world, route_name='hello')
app = config.make_wsgi_app()
server = make_server('0.0.0.0', 6543, app)
server.serve_forever()
webargs.pyramidparser.
PyramidParser
(locations=None, error_handler=None, schema_class=None)[source]¶Pyramid request argument parser.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error.
Pull the value from the cookiejar.
use_args
(argmap, req=None, locations=('querystring', 'form', 'json'), as_kwargs=False, validate=None, error_status_code=None, error_headers=None)[source]¶Decorator that injects parsed arguments into a view callable.
Supports the Class-based View pattern where request
is saved as an instance
attribute on a view class.
argmap (dict) – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse. Pulled off of the view by default.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
error_status_code (int) – Status code passed to error handler functions when
a ValidationError
is raised.
error_headers (dict) – Headers passed to error handler functions when a
a ValidationError
is raised.
webargs.pyramidparser.
use_args
(argmap, req=None, locations=('querystring', 'form', 'json'), as_kwargs=False, validate=None, error_status_code=None, error_headers=None)¶Decorator that injects parsed arguments into a view callable.
Supports the Class-based View pattern where request
is saved as an instance
attribute on a view class.
argmap (dict) – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse. Pulled off of the view by default.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
error_status_code (int) – Status code passed to error handler functions when
a ValidationError
is raised.
error_headers (dict) – Headers passed to error handler functions when a
a ValidationError
is raised.
Webapp2 request argument parsing module.
Example:
import webapp2
from marshmallow import fields
from webargs.webobparser import use_args
hello_args = {
'name': fields.Str(missing='World')
}
class MainPage(webapp2.RequestHandler):
@use_args(hello_args)
def get_args(self, args):
self.response.write('Hello, {name}!'.format(name=args['name']))
@use_kwargs(hello_args)
def get_kwargs(self, name=None):
self.response.write('Hello, {name}!'.format(name=name))
app = webapp2.WSGIApplication([
webapp2.Route(r'/hello', MainPage, handler_method='get_args'),
webapp2.Route(r'/hello_dict', MainPage, handler_method='get_kwargs'),
], debug=True)
Falcon request argument parsing module.
webargs.falconparser.
FalconParser
(locations=None, error_handler=None, schema_class=None)[source]¶Falcon request argument parser.
get_request_from_view_args
(view, args, kwargs)[source]¶Get request from a resource method’s arguments. Assumes that request is the second argument.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing.
Pull a cookie value from the request.
parse_files
(req, name, field)[source]¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, field)[source]¶Pull a form value from the request.
Note
The request stream will be read and left at EOF.
aiohttp request argument parsing module.
Example:
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_args
hello_args = {
'name': fields.Str(required=True)
}
@asyncio.coroutine
@use_args(hello_args)
def index(request, args):
return web.Response(
body='Hello {}'.format(args['name']).encode('utf-8')
)
app = web.Application()
app.router.add_route('GET', '/', index)
webargs.aiohttpparser.
AIOHTTPParser
(locations=None, error_handler=None, schema_class=None)[source]¶aiohttp request argument parser.
get_request_from_view_args
(view: Callable, args: Iterable, kwargs: Mapping) → aiohttp.web_request.Request[source]¶Get request object from a handler function or method. Used internally by
use_args
and use_kwargs
.
handle_error
(error: marshmallow.exceptions.ValidationError, req: aiohttp.web_request.Request, schema: marshmallow.schema.Schema, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = None) → NoReturn[source]¶Handle ValidationErrors and return a JSON response of error messages to the client.
Pull a value from the cookiejar.
parse_files
(req: aiohttp.web_request.Request, name: str, field: marshmallow.fields.Field) → None[source]¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req: aiohttp.web_request.Request, name: str, field: marshmallow.fields.Field) → Any[source]¶Pull a form value from the request.
parse_headers
(req: aiohttp.web_request.Request, name: str, field: marshmallow.fields.Field) → Any[source]¶Pull a value from the header data.
parse_json
(req: aiohttp.web_request.Request, name: str, field: marshmallow.fields.Field) → Any[source]¶Pull a json value from the request.
webargs.aiohttpparser.
HTTPUnprocessableEntity
(*, headers: Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy, None] = None, reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, content_type: Optional[str] = None)[source]¶Copyright 2014-2019 Steven Loria and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
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.
Steven Loria <sloria1@gmail.com>
Jérôme Lafréchoux <https://github.com/lafrech>
@venuatu <https://github.com/venuatu>
Javier Santacruz @jvrsantacruz <javier.santacruz.lc@gmail.com>
Josh Carp <https://github.com/jmcarp>
@philtay <https://github.com/philtay>
Andriy Yurchuk <https://github.com/Ch00k>
Stas Sușcov <https://github.com/stas>
Josh Johnston <https://github.com/Trii>
Rory Hart <https://github.com/hartror>
Jace Browning <https://github.com/jacebrowning>
@marcellarius <https://github.com/marcellarius>
Damian Heard <https://github.com/DamianHeard>
Daniel Imhoff <https://github.com/dwieeb>
immerrr <https://github.com/immerrr>
Brett Higgins <https://github.com/brettdh>
Vlad Frolov <https://github.com/frol>
Tuukka Mustonen <https://github.com/tuukkamustonen>
Francois-Xavier Darveau <https://github.com/EFF>
Jérôme Lafréchoux <https://github.com/lafrech>
@DmitriyS <https://github.com/DmitriyS>
Svetlozar Argirov <https://github.com/zaro>
Florian S. <https://github.com/nebularazer>
@daniel98321 <https://github.com/daniel98321>
@Itayazolay <https://github.com/Itayazolay>
@Reskov <https://github.com/Reskov>
@cedzz <https://github.com/cedzz>
Moukayed (כוכב) <https://github.com/kochab>
Xiaoyu Lee <https://github.com/lee3164>
Jonathan Angelo <https://github.com/jangelo>
@zhenhua32 <https://github.com/zhenhua32>
Martin Roy <https://github.com/lindycoder>
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
…should all be reported on the GitHub Issue Tracker .
…should be released as a separate package.
Pull requests adding support for another framework will not be accepted. In order to keep webargs small and easy to maintain, we are not currently adding support for more frameworks. Instead, release your framework integration as a separate package and add it to the Ecosystem page in the GitHub wiki .
Fork webargs on GitHub.
$ git clone https://github.com/marshmallow-code/webargs.git
$ cd webargs
Install development requirements. It is highly recommended that you use a virtualenv. Use the following command to install an editable version of webargs along with its development requirements.
# After activating your virtualenv
$ pip install -e '.[dev]'
(Optional, but recommended) Install the pre-commit hooks, which will format and lint your git staged files.
# The pre-commit CLI was installed above
$ pre-commit install
Note
webargs uses black for code formatting, which is only compatible with Python>=3.6. Therefore, the pre-commit hooks require a minimum Python version of 3.6.
Webargs abides by the following branching model:
dev
Current development branch. New features should branch off here.
X.Y-line
Maintenance branch for release X.Y
. Bug fixes should be sent to the most recent release branch.. The maintainer will forward-port the fix to dev
. Note: exceptions may be made for bug fixes that introduce large code changes.
Always make a new branch for your work, no matter how small. Also, do not put unrelated changes in the same branch or pull request. This makes it more difficult to merge your changes.
Create a new local branch.
# For a new feature
$ git checkout -b name-of-feature dev
# For a bugfix
$ git checkout -b fix-something 1.2-line
Commit your changes. Write good commit messages.
$ git commit -m "Detailed commit message"
$ git push origin name-of-feature
Before submitting a pull request, check the following:
If the pull request adds functionality, it is tested and the docs are updated.
You’ve added yourself to AUTHORS.rst
.
4. Submit a pull request to marshmallow-code:dev
or the appropriate maintenance branch.
The CI build must be passing before your pull request is merged.
To run all tests:
$ pytest
To run syntax checks:
$ tox -e lint
(Optional) To run tests in all supported Python versions in their own virtual environments (must have each interpreter installed):
$ tox
Contributions to the documentation are welcome. Documentation is written in reStructured Text (rST). A quick rST reference can be found here. Builds are powered by Sphinx.
To build the docs in “watch” mode:
$ tox -e watch-docs
Changes in the docs/
directory will automatically trigger a rebuild.