API

webargs.core

class webargs.core.Parser(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = None)[source]

Base parser class that provides high-level implementation for parsing a request.

Descendant classes must provide lower-level implementations for reading data from different locations, e.g. load_json, load_querystring, etc.

Parameters
  • location (str) – Default location to use for data

  • unknown (str) – A default value to pass for unknown when calling the schema’s load method. Defaults to EXCLUDE for non-body locations and RAISE for request bodies. Pass None to use the schema’s setting instead.

  • error_handler (callable) – Custom error handler function.

DEFAULT_LOCATION: str = 'json'

Default location to check for data

DEFAULT_SCHEMA_CLASS

alias of marshmallow.schema.Schema

DEFAULT_VALIDATION_MESSAGE: str = 'Invalid value.'

Default error message for validation errors

DEFAULT_VALIDATION_STATUS: int = 422

Default status code to return for validation errors

KNOWN_MULTI_FIELDS: List[Type] = [<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>]

field types which should always be treated as if they set is_multiple=True

error_handler(func: Callable[[...], NoReturn])Callable[[...], NoReturn][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, *, error_status_code, error_headers):
    raise CustomError(error.messages)
Parameters

func (callable) – The error callback to register.

get_default_request()Optional[webargs.core.Request][source]

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

get_request_from_view_args(view: Callable, args: Tuple, kwargs: Mapping[str, Any])Optional[webargs.core.Request][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: marshmallow.exceptions.ValidationError, req: webargs.core.Request, schema: marshmallow.schema.Schema, *, error_status_code: int, error_headers: Mapping[str, str])NoReturn[source]

Called if an error occurs while parsing args. By default, just logs and raises error.

load_cookies(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load the cookies from the request or return missing if no value can be found.

load_files(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load files from the request or return missing if no values can be found.

load_form(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load the form data of a request object or return missing if no value can be found.

load_headers(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load the headers or return missing if no value can be found.

load_json(req: webargs.core.Request, schema: marshmallow.schema.Schema)Any[source]

Load JSON from a request object or return missing if no value can be found.

load_json_or_form(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load data from a request, accepting either JSON or form-encoded data.

The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.

load_querystring(req: webargs.core.Request, schema: marshmallow.schema.Schema)[source]

Load the query string of a request object or return missing if no value can be found.

location_loader(name: str)[source]

Decorator that registers a function for loading a request location. The wrapped function receives a schema and a request.

The schema will usually not be relevant, but it’s important in some cases – most notably in order to correctly load multidict values into list fields. Without the schema, there would be no way to know whether to simply get() or getall() from a multidict for a given value.

Example:

from webargs import core
parser = core.Parser()

@parser.location_loader("name")
def load_data(request, schema):
    return request.data
Parameters

name (str) – The name of the location to register.

parse(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field], Callable[[webargs.core.Request], marshmallow.schema.Schema]], req: Optional[webargs.core.Request] = None, *, location: Optional[str] = None, unknown: Optional[str] = '_default', validate: Union[None, Callable, Iterable[Callable]] = None, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = 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.

  • location (str) – Where on the request to load values. Can be any of the values in __location_map__. By default, that means one of ('json', 'query', 'querystring', 'form', 'headers', 'cookies', 'files', 'json_or_form').

  • unknown (str) – A value to pass for unknown when calling the schema’s load method. Defaults to EXCLUDE for non-body locations and RAISE for request bodies. Pass None to use the schema’s setting instead.

  • 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) –

    Headers passed to error handler functions when a

    a ValidationError is raised.

    return

    A dictionary of parsed arguments

pre_load(location_data: collections.abc.Mapping, *, schema: marshmallow.schema.Schema, req: webargs.core.Request, location: str)collections.abc.Mapping[source]

A method of the parser which can transform data after location loading is done. By default it does nothing, but users can subclass parsers and override this method.

use_args(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field], Callable[[webargs.core.Request], marshmallow.schema.Schema]], req: Optional[webargs.core.Request] = None, *, location: Optional[str] = None, unknown: Optional[str] = '_default', as_kwargs: bool = False, validate: Union[None, 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.

Example usage with Flask:

@app.route('/echo', methods=['get', 'post'])
@parser.use_args({'name': fields.Str()}, location="querystring")
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.

  • location (str) – Where on the request to load values.

  • unknown (str) – A value to pass for unknown when calling the schema’s load method.

  • 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)Callable[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().

exception webargs.core.ValidationError(message: Union[str, List, Dict], field_name: str = '_schema', data: Optional[Union[Mapping[str, Any], Iterable[Mapping[str, Any]]]] = None, valid_data: Optional[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.

Parameters
  • 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.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"),
}
class webargs.fields.DelimitedList(cls_or_instance: Union[marshmallow.fields.Field, type], *, delimiter: Optional[str] = None, **kwargs)[source]

A field which is similar to a List, but takes its input as a delimited string (e.g. “foo,bar,baz”).

Like List, it can be given a nested field type which it will use to de/serialize each element of the list.

Parameters
  • cls_or_instance (Field) – A field class or instance.

  • delimiter (str) – Delimiter between values.

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.

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

class webargs.multidictproxy.MultiDictProxy(multidict, schema: marshmallow.schema.Schema, known_multi_fields: Tuple[Type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]

A proxy object which wraps multidict types along with a matching schema Whenever a value is looked up, it is checked against the schema to see if there is a matching field where is_multiple is True. If there is, then the data should be loaded as a list or tuple.

In all other cases, __getitem__ proxies directly to the input multidict.

webargs.asyncparser

Asynchronous request parser.

class webargs.asyncparser.AsyncParser(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = 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

error_handler(func: Callable[[...], NoReturn])Callable[[...], NoReturn]

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, *, error_status_code, error_headers):
    raise CustomError(error.messages)
Parameters

func (callable) – The error callback to register.

get_default_request()Optional[webargs.core.Request]

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

get_request_from_view_args(view: Callable, args: Tuple, kwargs: Mapping[str, Any])Optional[webargs.core.Request]

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: marshmallow.exceptions.ValidationError, req: webargs.core.Request, schema: marshmallow.schema.Schema, *, error_status_code: int, error_headers: Mapping[str, str])NoReturn

Called if an error occurs while parsing args. By default, just logs and raises error.

load_cookies(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load the cookies from the request or return missing if no value can be found.

load_files(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load files from the request or return missing if no values can be found.

load_form(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load the form data of a request object or return missing if no value can be found.

load_headers(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load the headers or return missing if no value can be found.

load_json(req: webargs.core.Request, schema: marshmallow.schema.Schema)Any

Load JSON from a request object or return missing if no value can be found.

load_json_or_form(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load data from a request, accepting either JSON or form-encoded data.

The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.

load_querystring(req: webargs.core.Request, schema: marshmallow.schema.Schema)

Load the query string of a request object or return missing if no value can be found.

location_loader(name: str)

Decorator that registers a function for loading a request location. The wrapped function receives a schema and a request.

The schema will usually not be relevant, but it’s important in some cases – most notably in order to correctly load multidict values into list fields. Without the schema, there would be no way to know whether to simply get() or getall() from a multidict for a given value.

Example:

from webargs import core
parser = core.Parser()

@parser.location_loader("name")
def load_data(request, schema):
    return request.data
Parameters

name (str) – The name of the location to register.

async parse(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field], Callable[[webargs.core.Request], marshmallow.schema.Schema]], req: Optional[webargs.core.Request] = None, *, location: Optional[str] = None, unknown: Optional[str] = '_default', validate: Union[None, 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.

pre_load(location_data: collections.abc.Mapping, *, schema: marshmallow.schema.Schema, req: webargs.core.Request, location: str)collections.abc.Mapping

A method of the parser which can transform data after location loading is done. By default it does nothing, but users can subclass parsers and override this method.

use_args(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field], Callable[[webargs.core.Request], marshmallow.schema.Schema]], req: Optional[webargs.core.Request] = None, *, location: Optional[str] = None, unknown='_default', as_kwargs: bool = False, validate: Union[None, 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

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

Flask request argument parsing module.

Example:

from flask import Flask

from webargs import fields
from webargs.flaskparser import use_args

app = Flask(__name__)

user_detail_args = {
    'per_page': fields.Int()
}

@app.route("/user/<int:uid>")
@use_args(user_detail_args)
def user_detail(args, uid):
    return ("The user page for user {uid}, showing {per_page} posts.").format(
        uid=uid, per_page=args["per_page"]
    )
class webargs.flaskparser.FlaskParser(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = None)[source]

Flask request argument parser.

get_default_request()[source]

Override to use Flask’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 HTTP request and responds with a 422 error.

load_cookies(req, schema)[source]

Return cookies from the request.

load_files(req, schema)[source]

Return files from the request as a MultiDictProxy.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema)[source]

Return headers from the request as a MultiDictProxy.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

load_view_args(req, schema)[source]

Return the request’s view_args or missing if there are none.

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(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = 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.

load_cookies(req, schema)[source]

Return cookies from the request.

load_files(req, schema)[source]

Return files from the request as a MultiDictProxy.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema)[source]

Return headers from the request.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

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(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = 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.

load_cookies(req, schema)[source]

Return cookies from the request.

load_files(req, schema)[source]

Return files from the request as a MultiDictProxy.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema)[source]

Return headers from the request as a MultiDictProxy.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

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(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = 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.

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.

load_cookies(req, schema)[source]

Return cookies from the request as a MultiDictProxy.

load_files(req, schema)[source]

Return files from the request as a MultiDictProxy.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema)[source]

Return headers from the request as a MultiDictProxy.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

class webargs.tornadoparser.WebArgsTornadoCookiesMultiDictProxy(multidict, schema: marshmallow.schema.Schema, known_multi_fields: Tuple[Type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]

And a special override for cookies because they come back as objects with a value attribute we need to extract. Also, does not use the _unicode decoding step

class webargs.tornadoparser.WebArgsTornadoMultiDictProxy(multidict, schema: marshmallow.schema.Schema, known_multi_fields: Tuple[Type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]

Override class for Tornado multidicts, handles argument decoding requirements.

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(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = 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.

load_cookies(req, schema)[source]

Return cookies from the request as a MultiDictProxy.

load_files(req, schema)[source]

Return files from the request as a MultiDictProxy.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema)[source]

Return headers from the request as a MultiDictProxy.

load_matchdict(req, schema)[source]

Return the request’s matchdict as a MultiDictProxy.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

use_args(argmap, req=None, *, location='json', unknown=None, 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.

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.

  • location (str) – Where on the request to load values.

  • unknown (str) – A value to pass for unknown when calling the schema’s load method.

  • 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, *, location='json', unknown=None, 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.

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.

  • location (str) – Where on the request to load values.

  • unknown (str) – A value to pass for unknown when calling the schema’s load method.

  • 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.falconparser

Falcon request argument parsing module.

class webargs.falconparser.FalconParser(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = None)[source]

Falcon request argument parser.

Defaults to using the media location. See load_media() for details on the media location.

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.

load_cookies(req, schema)[source]

Return cookies from the request.

load_files(req, schema)[source]

Load files from the request or return missing if no values can be found.

load_form(req, schema)[source]

Return form values from the request as a MultiDictProxy

Note

The request stream will be read and left at EOF.

load_headers(req, schema)[source]

Return headers from the request.

load_media(req, schema)[source]

Return data unpacked and parsed by one of Falcon’s media handlers. By default, Falcon only handles JSON payloads.

To configure additional media handlers, see the Falcon documentation on media types.

Note

The request stream will be read and left at EOF.

load_querystring(req, schema)[source]

Return query params from the request as a MultiDictProxy.

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(location: Optional[str] = None, *, unknown: Optional[str] = '_default', error_handler: Optional[Callable[[...], NoReturn]] = None, schema_class: Optional[Type] = None)[source]

aiohttp request argument parser.

get_request_from_view_args(view: Callable, args: Iterable, kwargs: Mapping)[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, schema: marshmallow.schema.Schema, *, error_status_code: Optional[int], error_headers: Optional[Mapping[str, str]])NoReturn[source]

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

load_cookies(req, schema: marshmallow.schema.Schema)webargs.multidictproxy.MultiDictProxy[source]

Return cookies from the request as a MultiDictProxy.

load_files(req, schema: marshmallow.schema.Schema)NoReturn[source]

Load files from the request or return missing if no values can be found.

async load_form(req, schema: marshmallow.schema.Schema)webargs.multidictproxy.MultiDictProxy[source]

Return form values from the request as a MultiDictProxy.

load_headers(req, schema: marshmallow.schema.Schema)webargs.multidictproxy.MultiDictProxy[source]

Return headers from the request as a MultiDictProxy.

async load_json(req, schema: marshmallow.schema.Schema)[source]

Return a parsed json payload from the request.

async load_json_or_form(req, schema: marshmallow.schema.Schema)Union[Dict, webargs.multidictproxy.MultiDictProxy][source]

Load data from a request, accepting either JSON or form-encoded data.

The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.

load_match_info(req, schema: marshmallow.schema.Schema)Mapping[source]

Load the request’s match_info.

load_querystring(req, schema: marshmallow.schema.Schema)webargs.multidictproxy.MultiDictProxy[source]

Return query params from the request as a MultiDictProxy.

exception webargs.aiohttpparser.HTTPUnprocessableEntity(*, headers: Optional[Union[Mapping[Union[str, multidict._multidict.istr], str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy]] = None, reason: Optional[str] = None, body: Optional[Any] = None, text: Optional[str] = None, content_type: Optional[str] = None)[source]
Ecosystem License