webargs
webargs is a Python library for declarative parsing and validation of HTTP request objects. It provides built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, Falcon, and aiohttp. Leveraging Marshmallow under the hood, it offers a consistent API for defining request arguments and handling validation errors across different frameworks. The library is actively maintained, with the current stable version being 8.7.1.
Warnings
- breaking webargs 7.x dropped support for Marshmallow 2. Ensure your project is using Marshmallow 3.x or later.
- breaking The `dict2schema` helper function was removed in webargs 7.x.
- breaking The default behavior of the `unknown` parameter changed in webargs 8.x for `json`, `form`, and `json_or_form` locations. It now defaults to `None` instead of `RAISE` if not explicitly set. This means unknown fields might be silently ignored rather than raising an error.
- breaking webargs 7.x dropped support for Python 3.5 and webapp2.
- gotcha When integrating with Flask-RESTful, webargs' default error handling may return HTTP 500 errors for validation failures instead of JSON-formatted errors.
Install
-
pip install -U webargs
Imports
- fields
from webargs import fields
- use_args
from webargs.flaskparser import use_args
- Arg
from webargs import fields
- dict2schema
from marshmallow import Schema
Quickstart
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
@app.route("/")
@use_args({"name": fields.Str(required=True)}, location="query")
def index(args):
return "Hello " + args["name"]
if __name__ == "__main__":
# To run: python your_app.py
# Then try: curl "http://127.0.0.1:5000/?name=World"
app.run(debug=True)