API

webargs.core

exception webargs.core.WebargsError[source]

Base class for all webargs-related errors.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception webargs.core.ValidationError(message, status_code=None, headers=None, **kwargs)[source]

Raised when validation fails on user input.

Changed in version 4.2.0: status_code and headers arguments are deprecated. Pass error_status_code and error_headers to Parser.parse, Parser.use_args, and Parser.use_kwargs instead.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

webargs.core.dict2schema(dct)[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.

class webargs.core.Parser(locations=None, error_handler=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.

Parameters:
  • locations (tuple) – Default locations to parse.
  • error_handler (callable) – Custom error handler function.
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.

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)
Parameters: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.

Parameters:
  • 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)
Parameters:name (str) – The name of the location to register.
parse(argmap, req=None, locations=None, validate=None, force_all=False, error_status_code=None, error_headers=None)[source]

Main request parsing method.

Parameters:
  • 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.
  • force_all (bool) – If True, missing arguments will be replaced with missing.
  • 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.
    return: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.

Parameters:
  • 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.
Returns:

The unvalidated argument value or missing if the value cannot be found on the request.

parse_cookies(req, name, arg)[source]

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, force_all=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']
Parameters:
  • 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.
  • force_all (bool) – If True, missing arguments will be included in the parsed arguments dictionary with the missing value. If False, missing values will be omitted. If None, fall back to the value of as_kwargs.
  • 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().

webargs.core.get_value(data, name, field, allow_many_nested=False)[source]

Get a value from a dictionary. Handles MultiDict types when multiple=True. If the value is not found, return missing.

Parameters:
  • data (object) – Mapping (e.g. dict) or list-like instance to pull the value from.
  • name (str) – Name of the key.
  • multiple (bool) – Whether to handle multiple values.
  • allow_many_nested (bool) – Whether to allow a list of nested objects (it is valid only for JSON format, so it is set to True in parse_json methods).

webargs.fields

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.

class 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.

class 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”).

Parameters:
  • cls_or_instance (Field) – A field class or instance.
  • delimiter (str) – Delimiter between values.
  • as_string (bool) – Dump values to string.

webargs.asyncparser

Asynchronous request parser. Compatible with Python>=3.5.

class webargs.asyncparser.AsyncParser(locations=None, error_handler=None)[source]

Asynchronous variant of webargs.core.Parser, where parsing methods may be either coroutines or regular methods.

clear_cache()

Invalidate the parser’s cache.

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)
Parameters: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.

Parameters:
  • 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)
Parameters:name (str) – The name of the location to register.
parse(argmap, req=None, locations=None, validate=None, force_all=False, error_status_code=None, error_headers=None)[source]

Coroutine variant of webargs.core.Parser.

Receives the same arguments as webargs.core.Parser.parse.

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.

Parameters:
  • 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.
Returns:

The unvalidated argument value or missing if the value cannot be found on the request.

parse_cookies(req, name, arg)

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, req=None, locations=None, as_kwargs=False, validate=None, force_all=None, error_status_code=None, error_headers=None)[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)[source]

Decorator that injects parsed arguments into a view function or method.

Receives the same arguments as webargs.core.Parser.use_kwargs.

webargs.flaskparser

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']
class webargs.flaskparser.FlaskParser(locations=None, error_handler=None)[source]

Flask request argument parser.

get_default_request()[source]

Override to use Flask’s thread-local request objec by default

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.

parse_cookies(req, name, field)[source]

Pull a value from the cookiejar.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull a form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

parse_view_args(req, name, field)[source]

Pull a value from the request’s view_args.

webargs.flaskparser.abort(http_status_code, exc=None, **kwargs)[source]

Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.

From Flask-Restful. See NOTICE file for license information.

webargs.djangoparser

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'])
class webargs.djangoparser.DjangoParser(locations=None, error_handler=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.

Parameters:
  • 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.
parse_cookies(req, name, field)[source]

Pull the value from the cookiejar.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull the form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the headers or return missing if the value cannot be found.

parse_json(req, name, field)[source]

Pull a json value from the request body.

parse_querystring(req, name, field)[source]

Pull the querystring value from the request.

webargs.bottleparser

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)
class webargs.bottleparser.BottleParser(locations=None, error_handler=None)[source]

Bottle.py request argument parser.

get_default_request()[source]

Override to use bottle’s thread-local request object by default.

handle_error(error, req, schema, error_status_code, error_headers)[source]

Handles errors during parsing. Aborts the current request with a 400 error.

parse_cookies(req, name, field)[source]

Pull a value from the cookiejar.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull a form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

webargs.tornadoparser

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)
exception webargs.tornadoparser.HTTPError(*args, **kwargs)[source]

tornado.web.HTTPError that stores validation errors.

class webargs.tornadoparser.TornadoParser(*args, **kwargs)[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.

Parameters:
  • 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, error_headers)[source]

Handles errors during parsing. Raises a tornado.web.HTTPError with a 400 error.

parse_cookies(req, name, field)[source]

Pull a value from the header data.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull a form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

webargs.tornadoparser.decode_argument(value, name=None)[source]

Decodes an argument from the request.

webargs.tornadoparser.get_value(d, name, field)[source]

Handle gets from ‘multidicts’ made of lists

It handles cases: {"key": [value]} and {"key": value}

webargs.tornadoparser.parse_json_body(req)[source]

Return the decoded JSON body from the request.

webargs.pyramidparser

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()
class webargs.pyramidparser.PyramidParser(locations=None, error_handler=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.

parse_cookies(req, name, field)[source]

Pull the value from the cookiejar.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull a form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_matchdict(req, name, field)[source]

Pull a value from the request’s matchdict.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

use_args(argmap, req=None, locations=('querystring', 'form', 'json'), as_kwargs=False, validate=None, force_all=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.

Parameters:
  • 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.
  • force_all (bool) – If True, missing arguments will be included in the parsed arguments dictionary with the missing value. If False, missing values will be omitted. If None, fall back to the value of as_kwargs.
  • 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.webapp2parser

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)
class webargs.webapp2parser.Webapp2Parser(locations=None, error_handler=None)[source]

webapp2 request argument parser.

get_default_request()[source]

Optional override. Provides a hook for frameworks that use thread-local request objects.

parse_cookies(req, name, field)[source]

Pull the value from the cookiejar.

parse_files(req, name, field)[source]

Pull a file from the request.

parse_form(req, name, field)[source]

Pull a form value from the request.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

webargs.falconparser

Falcon request argument parsing module.

class webargs.falconparser.FalconParser(locations=None, error_handler=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.

parse_cookies(req, name, field)[source]

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.

parse_headers(req, name, field)[source]

Pull a header value from the request.

parse_json(req, name, field)[source]

Pull a JSON body value from the request.

Note

The request stream will be read and left at EOF.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

exception webargs.falconparser.HTTPError(status, errors, *args, **kwargs)[source]

HTTPError that stores a dictionary of validation error messages.

to_dict(*args, **kwargs)[source]

Override falcon.HTTPError to include error messages in responses.

webargs.aiohttpparser

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)
class webargs.aiohttpparser.AIOHTTPParser(locations=None, error_handler=None)[source]

aiohttp request argument parser.

get_request_from_view_args(view, args, kwargs)[source]

Get request object from a handler function or method. Used internally by use_args and use_kwargs.

handle_error(error, req, schema, error_status_code, error_headers)[source]

Handle ValidationErrors and return a JSON response of error messages to the client.

parse_cookies(req, name, field)[source]

Pull a value from the cookiejar.

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.

parse_headers(req, name, field)[source]

Pull a value from the header data.

parse_json(req, name, field)[source]

Pull a json value from the request.

parse_match_info(req, name, field)[source]

Pull a value from the request’s match_info.

parse_querystring(req, name, field)[source]

Pull a querystring value from the request.

exception webargs.aiohttpparser.HTTPUnprocessableEntity(*, headers: Union[Mapping[str, 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]