API — webargs 6.1.0 documentation
Description: Declarative parsing and validation of HTTP request objects.

# API

## webargs.core

class webargs.core.Parser(location=None, *, error_handler=None, schema_class=None)

  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

    - error_handler (callable) – Custom error handler function.

  DEFAULT_LOCATION = 'json'

    Default location 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

  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, error_headers)

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

  load_cookies(req, schema)

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

  load_files(req, schema)

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

  load_form(req, schema)

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

  load_headers(req, schema)

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

  load_json(req, schema)

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

  load_json_or_form(req, 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, schema)

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

  location_loader(name)

    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, req=None, *, location=None, validate=None, error_status_code=None, error_headers=None)

    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')`.

      - 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

  use_args(argmap, req=None, *, location=None, as_kwargs=False, validate=None, error_status_code=None, error_headers=None)

    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.

      - 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

    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)

  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.core.dict2schema(dct, *, schema_class=<class 'marshmallow.schema.Schema'>)

  Generate a `marshmallow.Schema` class given a dictionary of `Fields`.

webargs.core.is_multiple(field)

  Return whether or not `field` handles repeated/multi-value arguments.

## 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.DelimitedList(cls_or_instance, *, delimiter=None, **kwargs)

  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)

  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)

  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. Compatible with Python>=3.5.

class webargs.asyncparser.AsyncParser(location=None, *, error_handler=None, schema_class=None)

  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)

    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, error_headers)

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

  load_cookies(req, schema)

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

  load_files(req, schema)

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

  load_form(req, schema)

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

  load_headers(req, schema)

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

  load_json(req, schema)

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

  load_json_or_form(req, 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, schema)

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

  location_loader(name)

    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]], req: Optional[webargs.asyncparser.Request] = None, *, location: Optional[str] = None, validate: Optional[Union[Callable, Iterable[Callable]]] = None, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = None) → Optional[Mapping]

    Coroutine variant of `webargs.core.Parser`.

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

  use_args(argmap: Union[marshmallow.schema.Schema, Mapping[str, marshmallow.fields.Field]], req: Optional[webargs.asyncparser.Request] = None, *, location: Optional[str] = None, as_kwargs: bool = False, validate: Optional[Union[Callable, Iterable[Callable]]] = None, error_status_code: Optional[int] = None, error_headers: Optional[Mapping[str, str]] = None) → Callable[[...], Callable]

    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

## 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=None, *, error_handler=None, schema_class=None)

  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)

    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)

    Return cookies from the request.

  load_files(req, schema)

    Return files from the request as a MultiDictProxy.

  load_form(req, schema)

    Return form values from the request as a MultiDictProxy.

  load_headers(req, schema)

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

  load_querystring(req, schema)

    Return query params from the request as a MultiDictProxy.

## webargs.bottleparser

## webargs.tornadoparser

## webargs.pyramidparser

## webargs.webapp2parser

## webargs.falconparser

## webargs.aiohttpparser

← Ecosystem License →