webargs

webargs is a Python utility library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, and Tornado.

Release v0.6.1. (Changelog)

Useful Links:

webargs @ Github | webargs @ PyPI | Issue Tracker

Hello Webargs

from flask import Flask
from webargs import Arg
from webargs.flaskparser import use_args

app = Flask(__name__)

hello_args = {
    'name': Arg(str, default='World')
}

@app.route('/', methods=['get', 'post'])
@use_args(hello_args)
def index(args):
    return 'Hello ' + args['name']

if __name__ == '__main__':
    app.run()

Webargs will automatically parse:

URL 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

Framework support

  • Flask
  • Django
  • Bottle
  • Tornado

Why Use It

  • Simple to use. Uncertain whether user input will be present on request.form, request.data, request.args, or request.json? No problem; webargs will find the value for you.
  • 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.

Inspired by Flask-RESTful’s reqparser, webargs offers a lightweight, cross-framework solution to request parsing that’s simple and fun to use.

Install

webargs is small. It has no hard dependencies, so you can easily vendorize it within your project or install the latest version from the PyPI:

pip install -U webargs

webargs supports Python >= 2.6 or >= 3.3.

Usage Guide

Basic Usage

Arguments are specified as a dictionary of name -> Arg pairs. Arg objects take a number of optional arguments, e.g. for type conversion and validation.

from webargs import Arg

user_args = {

    'username': Arg(str, required=True),  # 400 error thrown if
                                          # required argument is missing

    # Validation function (`validate`)
    'password': Arg(str, validate=lambda p: len(p) > 6,
                    error='Invalid password'),

    # Conversion function (`use`)
    'fullname': Arg(str, use=lambda n: n.lower()),

    # Default value
    'display_per_page': Arg(int, default=10),

    # Repeated parameter, e.g. "/?nickname=Fred&nickname=Freddie"
    'nickname': Arg(str, multiple=True),

    # When you know where an argument should be parsed from
    'active': Arg(bool, target='querystring')
}

To parse request arguments, use the parse method of a Parser object.

from flask import request
from webargs.flaskparser import FlaskParser

parser = FlaskParser()

@app.route('/register')
def register():
    args = parser.parse(user_args, request)
    return register_user(args['username'], args['password'],
        fullname=args['fullname'], per_page=args['display_per_page'])

Alternatively, 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')
@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')
@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)

By default, webargs will search for arguments from the URL querystring (e.g. "/?name=foo"), form data, and JSON data (in that order). You can explicitly specify which targets to search, like so:

@app.route('/register')
@use_args(user_args, targets=('json', 'form'))
def register(args):
    return 'registration page'

Available targets include:

  • 'querystring'
  • 'json'
  • 'form'
  • 'headers'
  • 'cookies'
  • 'files'

Adding Custom Target Handlers

To add your own custom target handler, write a function that receives a request, an argument name, and an Arg object, then decorate that function with Parser.target_handler.

from webargs.flaskparser import parser

@parser.target_handler('data')
def parse_data(request, name, arg):
    return request.data.get(name)

# Now 'data' can be specified as a target

@parser.use_args({'per_page': Arg(int)}, targets=('data', ))
def posts(args):
    return 'displaying {} posts'.format(args['per_page'])

Validation

Each Arg object can be validated individually by passing the validate argument.

from webargs import Arg

args = {
    'age': Arg(int, validate=lambda val: val > 0)
}

The full arguments dictionary can also be validated by passing validate to Parser.parse(), Parser.use_args(), Parser.use_kwargs().

from webargs import Arg
from webargs.flaskparser import parser

args = {
    'age': Arg(int),
    'years_employed': Arg(int),
}

# ...
result = parser.parse(args,
                      validate=lambda args: args['years_employed'] < args['age'])

Handling Errors

Each parser has a default error handling method. To override the error handling callback, write a function that receives an error and handles it, then decorate that function with Parser.error_handler.

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)

Flask Support

Flask support is available via the webargs.flaskparser module.

Decorator Usage

When using the use_args decorator, the arguments dictionary will be before any URL variable parameters.

from webargs.flaskparser import use_args

@app.route('/user/<int:uid>')
@use_args({'per_page': Arg(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'])

Django Support

Django support is available via the webargs.djangoparser module.

Webargs can parse Django request arguments in both function-based and class-based views.

Decorator Usage

When using the use_args decorator, the arguments dictionary will always be the second parameter (after self or request).

Function-based Views

from django.http import HttpResponse
from webargs import Arg
from webargs.djangoparser import use_args

account_args = {
  'username': Arg(str),
  'password': Arg(str)
}

@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 Arg
from webargs.djangoparser import use_args

blog_args = {
    'title': Arg(str, use=lambda t: t.lower()),
    'author': Arg(str)
}

class BlogPostView(View):
    @use_args(blog_args)
    def get(self, args, request):
      blog_post = Post.objects.get(title__iexact=args['title'],
                                   author=args['author'])
      return render_to_response('post_template.html',
                                {'post': blog_post})

Tornado Support

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 Arg
from webargs.tornadoparser import parser


class HelloHandler(tornado.web.RequestHandler):

    hello_args = {
        'name': Arg(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()

Decorator Usage

When using the use_args decorator, the decorated method will have the dictionary of parsed arguments passed as a positional argument after self.

from webargs import Arg
from webargs.tornadoparser import use_args

class HelloHandler(tornado.web.RequestHandler):

    @use_args({'name': Arg(str)})
    def post(self, reqargs, id):
        response = {
            'message': 'Hello {}'.format(reqargs['name'])
        }
        self.write(response)

With use_kwargs, the parsed arguments will be injected as keyword arguments.

class HelloHandler(tornado.web.RequestHandler):

    @use_kwargs({'name': Arg(str)})
    def post(self, id, name):  # "name" is injected
        response = {
            'message': 'Hello {}'.format(name)
        }
        self.write(response)

API Reference

webargs.core

class webargs.core.Arg(type_=None, default=None, required=False, validate=None, use=None, multiple=False, error=None, allow_missing=False, target=None)

A request argument.

Parameters:
  • default – Default value for the argument. Used if the value is not found on the request.
  • type_ (type) – Value type. Will try to convert the passed in value to this type. If None, no type conversion will be performed.
  • validate (callable) – Callable (function or object with __call__ method defined) used for custom validation. Returns whether or not the value is valid.
  • use (callable) – Function used for converting or pre-processing the value. Defaults to noop. Example: use=lambda s: s.lower()
  • multiple (bool) – Return a list of values for the argument. Useful for querystrings or forms that pass multiple values to the same parameter, e.g. /?name=foo&name=bar
  • error (str) – Custom error message to use if validation fails.
  • allow_missing (bool) – If the argument is not found on the request, don’t include it in the parsed arguments dictionary.
  • target (str) – Where to pull the value off the request, e.g. 'json'.

Changed in version 0.5.0: The use callable is called before type conversion.

validated(value)

Convert and validate the given value according to the type_, use, and validate attributes.

Returns:The validated, converted value
Raises:ValidationError if validation fails
webargs.core.Missing = <webargs.core.missing>

Singleton object that represents a value that cannot be found on a request.

class webargs.core.Parser(targets=None, error_handler=None)

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

Descendant classes must provide lower-level implementations for parsing different targets, e.g. parse_json, parse_querystring, etc.

Parameters:
  • targets (tuple) – Default targets to parse.
  • error_handler (callable) – Custom error handler function.
TARGET_MAP = {'files': 'parse_files', 'cookies': 'parse_cookies', 'form': 'parse_form', 'querystring': 'parse_querystring', 'headers': 'parse_headers', 'json': 'parse_json'}

Maps target => method name

error_handler(func)

Decorator that registers a custom error handling function. The function should received the raised error. Overrides the parser’s handle_error method.

Example:

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)
Parameters:func (callable) – The error callback to register.
fallback(req, name, arg)

Called if all other parsing functions (parse_json, parse_form...) return Missing.

handle_error(error)

Called if an error occurs while parsing args.

parse(argmap, req, targets=None, validate=None)

Main request parsing method.

Parameters:
  • argmap (dict) – Dictionary of argname:Arg object pairs.
  • req – The request object to parse.
  • targets (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 that receives the dictionary of parsed arguments. If the function returns False, the parser will raise a ValidationError.
Returns:

A dictionary of parsed arguments

parse_arg(name, argobj, req, targets=None)

Parse a single argument.

Parameters:
  • name (str) – The name of the value.
  • argobj (Arg) – The Arg object.
  • req – The request object to parse.
  • targets (tuple) – The targets (‘json’, ‘querystring’, etc.) where to search for the value.
Returns:

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

Raises:

ValidationError if a validation function returns False or if a required argument is missing.

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.

target_handler(name)

Decorator that registers a function that parses a request target. The wrapped function receives a request, the name of the argument, and the Arg object.

Example:

from webargs import core
parser = core.Parser()

@parser.target_handler('name')
def parse_data(request, name, arg):
    return request.data.get(name)
Parameters:name (str) – The name of the target to register.
use_args(argmap, req=None, targets=None, as_kwargs=False, validate=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': Arg(str)})
def greet(args):
    return 'Hello ' + args['name']
Parameters:
  • argmap (dict) – Dictionary of argument_name:Arg object pairs.
  • targets (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.
use_kwargs(*args, **kwargs)

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': Arg(str)})
def greet(name):
    return 'Hello ' + name

Receives the same args and kwargs as use_args().

exception webargs.core.ValidationError(underlying_exception)

Raised in case of an argument validation error.

exception webargs.core.WebargsError

Base class for all webargs-related errors.

webargs.core.get_value(d, name, multiple)

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

Parameters:
  • d (dict) – Dictionary to pull the value from.
  • name (str) – Name of the key.
  • multiple (bool) – Whether to handle multiple values.

webargs.flaskparser

Flask request argument parsing module.

Example:

from flask import Flask
from webargs import Arg
from webargs.flaskparser import use_args

app = Flask(__name__)

hello_args = {
    'name': Arg(str, required=True)
}

@app.route('/')
@use_args(hello_args)
def index(args):
    return 'Hello ' + args['name']
class webargs.flaskparser.FlaskParser(targets=None, error_handler=None)

Flask request argument parser.

error_handler(func)

Decorator that registers a custom error handling function. The function should received the raised error. Overrides the parser’s handle_error method.

Example:

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)
Parameters:func (callable) – The error callback to register.
fallback(req, name, arg)

Called if all other parsing functions (parse_json, parse_form...) return Missing.

handle_error(error)

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

parse(argmap, req=None, *args, **kwargs)

Parses the request using the given arguments map. Uses Flask’s context-local request object if req=None.

parse_arg(name, argobj, req, targets=None)

Parse a single argument.

Parameters:
  • name (str) – The name of the value.
  • argobj (Arg) – The Arg object.
  • req – The request object to parse.
  • targets (tuple) – The targets (‘json’, ‘querystring’, etc.) where to search for the value.
Returns:

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

Raises:

ValidationError if a validation function returns False or if a required argument is missing.

parse_cookies(req, name, arg)

Pull a value from the cookiejar.

parse_files(req, name, arg)

Pull a file from the request.

parse_form(req, name, arg)

Pull a form value from the request.

parse_headers(req, name, arg)

Pull a value from the header data.

parse_json(req, name, arg)

Pull a json value from the request.

parse_querystring(req, name, arg)

Pull a querystring value from the request.

target_handler(name)

Decorator that registers a function that parses a request target. The wrapped function receives a request, the name of the argument, and the Arg object.

Example:

from webargs import core
parser = core.Parser()

@parser.target_handler('name')
def parse_data(request, name, arg):
    return request.data.get(name)
Parameters:name (str) – The name of the target to register.
use_args(argmap, req=None, targets=None, as_kwargs=False, validate=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': Arg(str)})
def greet(args):
    return 'Hello ' + args['name']
Parameters:
  • argmap (dict) – Dictionary of argument_name:Arg object pairs.
  • targets (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.
use_kwargs(*args, **kwargs)

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': Arg(str)})
def greet(name):
    return 'Hello ' + name

Receives the same args and kwargs as use_args().

webargs.flaskparser.abort(http_status_code, **kwargs)

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 webargs import Arg
from webargs.djangoparser import use_args

hello_args = {
    'name': Arg(str, default='World')
}

class MyView(View):

    @use_args(hello_args)
    def get(self, args, request):
        return HttpResponse('Hello ' + args['name'])
class webargs.djangoparser.DjangoParser(targets=None, error_handler=None)

Django request argument parser.

error_handler(func)

Decorator that registers a custom error handling function. The function should received the raised error. Overrides the parser’s handle_error method.

Example:

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)
Parameters:func (callable) – The error callback to register.
fallback(req, name, arg)

Called if all other parsing functions (parse_json, parse_form...) return Missing.

handle_error(error)

Called if an error occurs while parsing args.

parse(argmap, req, targets=None, validate=None)

Main request parsing method.

Parameters:
  • argmap (dict) – Dictionary of argname:Arg object pairs.
  • req – The request object to parse.
  • targets (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 that receives the dictionary of parsed arguments. If the function returns False, the parser will raise a ValidationError.
Returns:

A dictionary of parsed arguments

parse_arg(name, argobj, req, targets=None)

Parse a single argument.

Parameters:
  • name (str) – The name of the value.
  • argobj (Arg) – The Arg object.
  • req – The request object to parse.
  • targets (tuple) – The targets (‘json’, ‘querystring’, etc.) where to search for the value.
Returns:

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

Raises:

ValidationError if a validation function returns False or if a required argument is missing.

parse_cookies(req, name, arg)

Pull the value from the cookiejar.

parse_files(req, name, arg)

Pull a file from the request.

parse_form(req, name, arg)

Pull the form value from the request.

parse_json(req, name, arg)

Pull a json value from the request body.

parse_querystring(req, name, arg)

Pull the querystring value from the request.

target_handler(name)

Decorator that registers a function that parses a request target. The wrapped function receives a request, the name of the argument, and the Arg object.

Example:

from webargs import core
parser = core.Parser()

@parser.target_handler('name')
def parse_data(request, name, arg):
    return request.data.get(name)
Parameters:name (str) – The name of the target to register.
use_args(argmap, req=None, targets=('querystring', 'form', 'json'), validate=None)

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

Example:

@parser.use_args({'name': 'World'})
def myview(request, args):
    return HttpResponse('Hello ' + args['name'])
Parameters:
  • argmap (dict) – Dictionary of argument_name:Arg object pairs.
  • req – The request object to parse
  • targets (tuple) – Where on the request to search for values.
  • validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns False, the parser will raise a ValidationError.
use_kwargs(*args, **kwargs)

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': Arg(str)})
def greet(name):
    return 'Hello ' + name

Receives the same args and kwargs as use_args().

webargs.bottleparser

Bottle request argument parsing module.

Example:

from bottle import route
from webargs import Arg
from webargs.bottleparser import use_args

hello_args = {
    'name': Arg(str, default='World')
}

@route('/', method=['GET', 'POST'])
@use_args(hello_args)
def index(args)
    return 'Hello ' + args['name']
class webargs.bottleparser.BottleParser(targets=None, error_handler=None)

Bottle.py request argument parser.

error_handler(func)

Decorator that registers a custom error handling function. The function should received the raised error. Overrides the parser’s handle_error method.

Example:

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)
Parameters:func (callable) – The error callback to register.
fallback(req, name, arg)

Called if all other parsing functions (parse_json, parse_form...) return Missing.

handle_error(error)

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

parse(argmap, req=None, *args, **kwargs)

Parses the request using the given arguments map. Uses Bottle’s context-local request object if req=None.

parse_arg(name, argobj, req, targets=None)

Parse a single argument.

Parameters:
  • name (str) – The name of the value.
  • argobj (Arg) – The Arg object.
  • req – The request object to parse.
  • targets (tuple) – The targets (‘json’, ‘querystring’, etc.) where to search for the value.
Returns:

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

Raises:

ValidationError if a validation function returns False or if a required argument is missing.

parse_cookies(req, name, arg)

Pull a value from the cookiejar.

parse_files(req, name, arg)

Pull a file from the request.

parse_form(req, name, arg)

Pull a form value from the request.

parse_headers(req, name, arg)

Pull a value from the header data.

parse_json(req, name, arg)

Pull a json value from the request.

parse_querystring(req, name, arg)

Pull a querystring value from the request.

target_handler(name)

Decorator that registers a function that parses a request target. The wrapped function receives a request, the name of the argument, and the Arg object.

Example:

from webargs import core
parser = core.Parser()

@parser.target_handler('name')
def parse_data(request, name, arg):
    return request.data.get(name)
Parameters:name (str) – The name of the target to register.
use_args(argmap, req=None, targets=None, as_kwargs=False, validate=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': Arg(str)})
def greet(args):
    return 'Hello ' + args['name']
Parameters:
  • argmap (dict) – Dictionary of argument_name:Arg object pairs.
  • targets (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.
use_kwargs(*args, **kwargs)

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': Arg(str)})
def greet(name):
    return 'Hello ' + name

Receives the same args and kwargs as use_args().

webargs.tornadoparser

Tornado request argument parsing module.

Example:

import tornado.web
from webargs import Arg
from webargs.tornadoparser import use_args

class HelloHandler(tornado.web.RequestHandler):

    @use_args({'name': Arg(str)})
    def get(self, args):
        response = {'message': 'Hello {}'.format(args['name'])}
        self.write(response)
class webargs.tornadoparser.TornadoParser(targets=None, error_handler=None)

Tornado request argument parser.

error_handler(func)

Decorator that registers a custom error handling function. The function should received the raised error. Overrides the parser’s handle_error method.

Example:

from webargs import core
parser = core.Parser()

class CustomError(Exception):
    pass

@parser.error_handler
def handle_error(error):
    raise CustomError(error)
Parameters:func (callable) – The error callback to register.
fallback(req, name, arg)

Called if all other parsing functions (parse_json, parse_form...) return Missing.

handle_error(error)

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

parse(argmap, req, *args, **kwargs)

Parses the request using the given arguments map.

Initializes json attribute.

parse_arg(name, argobj, req, targets=None)

Parse a single argument.

Parameters:
  • name (str) – The name of the value.
  • argobj (Arg) – The Arg object.
  • req – The request object to parse.
  • targets (tuple) – The targets (‘json’, ‘querystring’, etc.) where to search for the value.
Returns:

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

Raises:

ValidationError if a validation function returns False or if a required argument is missing.

parse_cookies(req, name, arg)

Pull a value from the header data.

parse_files(req, name, arg)

Pull a file from the request.

parse_form(req, name, arg)

Pull a form value from the request.

parse_headers(req, name, arg)

Pull a value from the header data.

parse_json(req, name, arg)

Pull a json value from the request.

parse_querystring(req, name, arg)

Pull a querystring value from the request.

target_handler(name)

Decorator that registers a function that parses a request target. The wrapped function receives a request, the name of the argument, and the Arg object.

Example:

from webargs import core
parser = core.Parser()

@parser.target_handler('name')
def parse_data(request, name, arg):
    return request.data.get(name)
Parameters:name (str) – The name of the target to register.
use_args(argmap, req=None, targets=('querystring', 'form', 'json'), as_kwargs=False, validate=None)

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

Parameters:
  • argmap (dict) – Dictionary of argument_name:Arg object pairs.
  • req – The request object to parse
  • targets (tuple) – Where on the request to search for values.
  • as_kwargs – Whether to pass arguments to the handler as kwargs
  • validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns False, the parser will raise a ValidationError.
use_kwargs(*args, **kwargs)

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': Arg(str)})
def greet(name):
    return 'Hello ' + name

Receives the same args and kwargs as use_args().

webargs.tornadoparser.get_value(d, name, multiple)

Handle gets from ‘multidicts’ made of lists

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

Fork me on GitHub