CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-webargs

Declarative parsing and validation of HTTP request objects, with built-in support for popular web frameworks.

Overview
Eval results
Files

framework-parsers.mddocs/

Framework Parsers

Framework-specific parser implementations that provide seamless integration with popular Python web frameworks. Each parser extends the core Parser class with framework-specific request handling, error responses, and integration patterns while maintaining a consistent API across all frameworks.

Capabilities

Flask Parser

Parser for Flask web framework with support for Flask request objects and error handling.

class FlaskParser(Parser[flask.Request]):
    """
    Parser for Flask framework.
    
    Integrates with Flask's request context and error handling system.
    Automatically detects Flask request objects and provides appropriate error responses.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = FlaskParser()

def use_args(argmap, req=None, **kwargs):
    """Flask-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Flask-specific use_kwargs decorator."""

def abort(http_status_code, exc=None, **kwargs):
    """Raise HTTPException with Flask-specific error handling."""

Django Parser

Parser for Django web framework with support for Django HttpRequest objects.

class DjangoParser(Parser[django.http.HttpRequest]):
    """
    Parser for Django framework.
    
    Integrates with Django's request/response cycle and error handling.
    Handles Django-specific request object structure and content types.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = DjangoParser()

def use_args(argmap, req=None, **kwargs):
    """Django-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Django-specific use_kwargs decorator."""

Bottle Parser

Parser for Bottle web framework with support for Bottle request objects.

class BottleParser(Parser[bottle.Request]):
    """
    Parser for Bottle framework.
    
    Integrates with Bottle's request handling and provides appropriate error responses.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = BottleParser()

def use_args(argmap, req=None, **kwargs):
    """Bottle-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Bottle-specific use_kwargs decorator."""

Tornado Parser

Parser for Tornado web framework with support for HTTPServerRequest objects.

class TornadoParser(Parser[tornado.httpserver.HTTPServerRequest]):
    """
    Parser for Tornado framework.
    
    Handles Tornado's request structure and provides framework-appropriate error responses.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = TornadoParser()

def use_args(argmap, req=None, **kwargs):
    """Tornado-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Tornado-specific use_kwargs decorator."""

Pyramid Parser

Parser for Pyramid web framework with support for Pyramid Request objects.

class PyramidParser(Parser[pyramid.request.Request]):
    """
    Parser for Pyramid framework.
    
    Integrates with Pyramid's request/response system and error handling.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = PyramidParser()

def use_args(argmap, req=None, **kwargs):
    """Pyramid-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Pyramid-specific use_kwargs decorator."""

Falcon Parser

Parser for Falcon web framework with support for Falcon Request objects.

class FalconParser(Parser[falcon.Request]):
    """
    Parser for Falcon framework.
    
    Handles Falcon's request structure and provides appropriate error responses.
    """
    def __init__(self, **kwargs): ...
    
    def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = FalconParser()

def use_args(argmap, req=None, **kwargs):
    """Falcon-specific use_args decorator."""

def use_kwargs(argmap, req=None, **kwargs):
    """Falcon-specific use_kwargs decorator."""

aiohttp Parser (Async)

Parser for aiohttp web framework with full async/await support.

class AIOHTTPParser(AsyncParser[aiohttp.web.Request]):
    """
    Parser for aiohttp framework with async support.
    
    Extends AsyncParser to provide async request parsing capabilities.
    All parsing operations are async-aware and integrate with aiohttp's async request handling.
    """
    def __init__(self, **kwargs): ...
    
    async def load_json(self, req, schema): ...
    def load_querystring(self, req, schema): ...
    async def load_form(self, req, schema): ...
    def load_headers(self, req, schema): ...
    def load_cookies(self, req, schema): ...
    def load_files(self, req, schema): ...
    async def load_json_or_form(self, req, schema): ...
    async def handle_error(self, error, req, schema, *, error_status_code, error_headers): ...

# Module-level parser instance and decorators
parser = AIOHTTPParser()

def use_args(argmap, req=None, **kwargs):
    """aiohttp-specific use_args decorator with async support."""

def use_kwargs(argmap, req=None, **kwargs):
    """aiohttp-specific use_kwargs decorator with async support."""

Async Parser Base

Base class for async-aware parsers that support coroutine-based parsing.

class AsyncParser(Parser[Request]):
    """
    Asynchronous variant of webargs.core.Parser.
    
    The parse method is redefined to be async and delegates to the async_parse method
    from the base Parser class. This provides a cleaner interface for async frameworks
    while maintaining compatibility with all the core parsing functionality.
    """
    async def parse(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):
        """
        Coroutine variant of webargs.core.Parser.parse.
        
        Receives the same arguments as webargs.core.Parser.parse but returns
        a coroutine that must be awaited.
        
        Args:
            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
            unknown (str): A value to pass for unknown when calling the schema's load method
            validate: Validation function or list of validation functions
            error_status_code (int): Status code passed to error handler functions
            error_headers (dict): Headers passed to error handler functions
            
        Returns:
            Any: A dictionary of parsed arguments
        """

Framework Integration Patterns

Flask Integration

from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args, use_kwargs

app = Flask(__name__)

@app.route("/users", methods=["POST"])
@use_args({"name": fields.Str(required=True)})
def create_user(args):
    return {"message": f"Created user {args['name']}"}

@app.route("/users/<int:user_id>", methods=["PUT"]) 
@use_kwargs({"name": fields.Str(), "email": fields.Email()})
def update_user(user_id, name=None, email=None):
    return {"message": f"Updated user {user_id}"}

Django Integration

from django.http import JsonResponse
from webargs import fields
from webargs.djangoparser import use_args, use_kwargs

@use_args({"q": fields.Str(location="query")})
def search_view(request, args):
    query = args["q"]
    # Search logic here
    return JsonResponse({"results": []})

@use_kwargs({"name": fields.Str(), "age": fields.Int()})
def user_view(request, name=None, age=None):
    return JsonResponse({"name": name, "age": age})

aiohttp Integration (Async)

from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_args, use_kwargs

@use_args({"name": fields.Str(required=True)})
async def create_user(request, args):
    name = args["name"]
    # Async database operations
    return web.json_response({"message": f"Created user {name}"})

@use_kwargs({"page": fields.Int(location="query", missing=1)})
async def list_users(request, page):
    # Async pagination logic
    return web.json_response({"page": page, "users": []})

Custom Parser Creation

from webargs.core import Parser

class CustomFrameworkParser(Parser):
    """Custom parser for a specific framework."""
    
    def load_json(self, req, schema):
        # Framework-specific JSON loading
        return req.get_json()
    
    def load_querystring(self, req, schema):
        # Framework-specific query parameter loading
        return self._makeproxy(req.args, schema)
    
    def handle_error(self, error, req, schema, *, error_status_code, error_headers):
        # Framework-specific error handling
        raise CustomFrameworkError(error.messages, error_status_code)

# Create parser instance and decorators
parser = CustomFrameworkParser()
use_args = parser.use_args
use_kwargs = parser.use_kwargs

Error Handling Patterns

Each framework parser provides appropriate error handling for the target framework:

  • Flask: Raises werkzeug.exceptions.HTTPException with error details
  • Django: Returns django.http.JsonResponse with error information
  • aiohttp: Returns aiohttp.web.Response with JSON error data
  • Tornado: Raises tornado.web.HTTPError with structured error messages
  • Pyramid: Raises pyramid.httpexceptions.HTTPBadRequest with error details
  • Falcon: Sets response status and JSON error body on response object
  • Bottle: Raises bottle.HTTPError with error information

Types

FlaskRequest = flask.Request
DjangoRequest = django.http.HttpRequest
BottleRequest = bottle.Request
TornadoRequest = tornado.httpserver.HTTPServerRequest
PyramidRequest = pyramid.request.Request
FalconRequest = falcon.Request
AIOHTTPRequest = aiohttp.web.Request

Install with Tessl CLI

npx tessl i tessl/pypi-webargs

docs

core-parsing.md

field-types.md

framework-parsers.md

index.md

testing-utilities.md

tile.json