webargs

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

Release v0.9.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
  • Pyramid

Why Use It

  • Simple, declarative syntax. Define your arguments as a mapping rather than imperatively pulling values off of request objects.
  • Code reusability. If you have multiple views that have the same request parameters, you only need to define your parameters once. You can also reuse validation and pre-processing routines.
  • Self-documentation. Webargs makes it easy to understand the expected arguments and their types for your view functions.
  • Automatic documentation. The metadata that webargs provides can serve as an aid for automatically generating API documentation.
  • Cross-framework compatibility. Webargs provides a consistent request-parsing interface that will work across the major Python web frameworks.

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.

Examples

See the examples directory for full examples using webargs.

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.

Below are examples of the various parameters that Arg objects can take.

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/postprocessing 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='query')

    # When value is keyed on a variable-unsafe name or you want to rename a key
    'content_type': Arg(str, source='Content-Type')
}

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' (same as 'query')
  • '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 validator may return either a boolean or raise a ValidationError.

def must_exist_in_db(val):
    if not User.query.get(val):
        # Optionally pass a status_code
        raise ValidationError('User does not exist', status_code=404)

args = {
    'id': Arg(int, validate=must_exist_in_db)
}

Note

You may also pass a list of validators to the validate parameter.

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)

Nesting Args

Arg dictionaries can be nested within each other. This can be useful for validating nested data.

args = {
    'name': Arg({
        'first': Arg(str, required=True),
        'last': Arg(str, required=True),
    })
}

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'])

Error Handling

Webargs uses Flask’s abort function to raise an HTTPException when a validation error occurs. If you use the Flask.errorhandler method to handle errors, you can access validation messages from the data attribute of an error.

Here is an example error handler that returns validation messages to the client as JSON.

from flask import jsonify

@app.errorhandler(400)
def handle_bad_request(err):
    # webargs attaches additional metadata to the `data` attribute
    data = getattr(err, 'data')
    if data:
        err_message = data['message']
    else:
        err_message = 'Invalid request'
    return jsonify({
        'message': err_message,
    }), 400

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})

Error Handling

The DjangoParser does not override handle_error, so your Django views are responsible for catching any ValidationErrors raised by the parser and returning the appropriate HTTPResponse.

from django.http import JsonResponse

from webargs import Arg, ValidationError

args = {
    'name': Arg(str, required=True)
}
def index(request):
    try:
        args = parser.parse(required_args, request)
    except ValidationError as err:
        return JsonResponse({'error': str(err)}, status=400)
    return JsonResponse({'message': 'Hello {name}'.format(name=name)})

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)

Pyramid Support

Pyramid support is available via the webargs.pyramidparser module.

Decorator Usage

When using the use_args decorator on a view callable, the arguments dictionary will be positioned after the request argument.

from pyramid.response import Response
from webargs.pyramidparser import use_args

@use_args({'per_page': Arg(int)})
def user_detail(request, args):
    return Response('The user page for user {uid}, '
            'showing {per_page} posts.').format(uid=uid,
                                                per_page=args['per_page']))

As with the other parser modules, use_kwargs will add keyword arguments to the view callable.

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, source=None, **metadata)[source]

A request argument.

Parameters:
  • type_ – Value type or nested Arg dictionary. If the former, the parsed value will be coerced this type. If the latter, the parsed value will be validated and converted according to the nested Arg dict. If None, no type conversion will be performed.
  • default – Default value for the argument. Used if the value is not found on the request. May be a callable.
  • required (bool) – If True, the Parser.handle_error() method will be invoked if this argument is missing from the request.
  • validate (callable) – Callable (function or object with __call__ method defined) or list of callables. used for custom validation. A validator may return a boolean or raise a ValidationError.
  • use (callable) – Function or list of functions 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'.
  • source (str) – Key at which value is located, if different from key in argmap
  • metadata – Extra arguments to be stored as metadata.

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

validated(name, value)[source]

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, error=None)[source]

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.
  • error (str) – Custom error message to use if validation fails.
clear_cache()[source]

Invalidate the parser’s cache.

error_handler(func)[source]

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)[source]

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

handle_error(error)[source]

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

parse(argmap, req, targets=None, validate=None, force_all=False)[source]

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 or list of validation functions
    that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a ValidationError.
    return:A dictionary of parsed arguments
parse_arg(name, argobj, req, targets=None)[source]

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)[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.

target_handler(name)[source]

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

Receives the same args and kwargs as use_args().

exception webargs.core.ValidationError(error, status_code=400, **data)[source]

Raised in case of an argument validation error.

Parameters:
  • error – Either a string message or an underlying Exception object.
  • status_code (int) – HTTP status code.
  • data – Additional keyword arguments to store in the data attribute.

Changed in version 0.8.0: Store status_code and additonal data.

exception webargs.core.WebargsError[source]

Base class for all webargs-related errors.

webargs.core.get_value(d, name, multiple)[source]

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, error=None)[source]

Flask request argument parser.

clear_cache()

Invalidate the parser’s cache.

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)[source]

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

parse(argmap, req=None, *args, **kwargs)[source]

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)[source]

Pull a value from the cookiejar.

parse_files(req, name, arg)[source]

Pull a file from the request.

parse_form(req, name, arg)[source]

Pull a form value from the request.

parse_headers(req, name, arg)[source]

Pull a value from the header data.

parse_json(req, name, arg)[source]

Pull a json value from the request.

parse_querystring(req, name, arg)[source]

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)[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 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, error=None)[source]

Django request argument parser.

Note

The DjangoParser does not override handle_error, so your Django views are responsible for catching any ValidationErrors raised by the parser and returning the appropriate HTTPResponse.

clear_cache()

Invalidate the parser’s cache.

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. By default, just logs and raises error.

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

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 or list of validation functions
    that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a ValidationError.
    return: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)[source]

Pull the value from the cookiejar.

parse_files(req, name, arg)[source]

Pull a file from the request.

parse_form(req, name, arg)[source]

Pull the form value from the request.

parse_json(req, name, arg)[source]

Pull a json value from the request body.

parse_querystring(req, name, arg)[source]

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=(u'querystring', u'form', u'json'), validate=None)[source]

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, run
from webargs import Arg
from webargs.bottleparser import use_args

hello_args = {
    'name': Arg(str, default='World')
}
@route('/', method='GET')
@use_args(hello_args)
def index(args):
    return 'Hello ' + args['name']

if __name__ == '__main__':
    run(debug=True)
class webargs.bottleparser.BottleParser(targets=None, error_handler=None, error=None)[source]

Bottle.py request argument parser.

clear_cache()

Invalidate the parser’s cache.

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)[source]

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

parse(argmap, req=None, *args, **kwargs)[source]

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)[source]

Pull a value from the cookiejar.

parse_files(req, name, arg)[source]

Pull a file from the request.

parse_form(req, name, arg)[source]

Pull a form value from the request.

parse_headers(req, name, arg)[source]

Pull a value from the header data.

parse_json(req, name, arg)[source]

Pull a json value from the request.

parse_querystring(req, name, arg)[source]

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, default='World')})
    def get(self, args):
        response = {'message': 'Hello {}'.format(args['name'])}
        self.write(response)
class webargs.tornadoparser.TornadoParser(*args, **kwargs)[source]

Tornado request argument parser.

clear_cache()

Invalidate the parser’s cache.

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)[source]

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

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

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 or list of validation functions
    that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a ValidationError.
    return: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)[source]

Pull a value from the header data.

parse_files(req, name, arg)[source]

Pull a file from the request.

parse_form(req, name, arg)[source]

Pull a form value from the request.

parse_headers(req, name, arg)[source]

Pull a value from the header data.

parse_json(req, name, arg)[source]

Pull a json value from the request.

parse_querystring(req, name, arg)[source]

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=(u'querystring', u'form', u'json'), as_kwargs=False, validate=None)[source]

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)[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 webargs import Arg
from webargs.pyramidparser import use_args

hello_args = {
    'name': Arg(str, default='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(targets=None, error_handler=None, error=None)[source]

Pyramid request argument parser.

clear_cache()

Invalidate the parser’s cache.

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)[source]

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

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

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 or list of validation functions
    that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a ValidationError.
    return: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)[source]

Pull the value from the cookiejar.

parse_files(req, name, arg)[source]

Pull a file from the request.

parse_form(req, name, arg)[source]

Pull a form value from the request.

parse_headers(req, name, arg)[source]

Pull a value from the header data.

parse_json(req, name, arg)[source]

Pull a json value from the request.

parse_querystring(req, name, arg)[source]

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=(u'querystring', u'form', u'json'), validate=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) – 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().

Suggested Pairings

If you are using webargs to handle input data for your HTTP API, you might consider using the marshmallow library for formatting your output data.

Fork me on GitHub