Sanic integration with Webargs

Overview

webargs-sanic

Sanic integration with Webargs.

Parsing and validating request arguments: headers, arguments, cookies, files, json, etc.

IMPORTANT: From version 2.0.0 webargs-sanic requires you to have webargs >=7.0.1. Please be aware of changes happened in version of webargs > 6.0.0. If you need support of webargs 5.x with no location definition, please use previous version(1.5.0) of this module from pypi.

Build Status Latest Version Python Versions Tests Coverage

webargs is a Python library for parsing and validating HTTP request arguments, with built-in support for popular web frameworks. webargs-sanic allows you to use it for Sanic apps. To read more about webargs usage, please check Quickstart

Example Code

Simple Application

from sanic import Sanic
from sanic.response import text

from webargs import fields
from webargs_sanic.sanicparser import use_args


app = Sanic(__name__)

hello_args = {
    'name': fields.Str(required=True)
}

@app.route('/')
@use_args(hello_args, location="query")
async def index(request, args):
    return text('Hello ' + args['name'])

Class-based Sanic app and args/kwargs

from sanic import Sanic
from sanic.views import HTTPMethodView
from sanic.response import json

from webargs import fields
from webargs_sanic.sanicparser import use_args, use_kwargs


app = Sanic(__name__)

class EchoMethodViewUseArgs(HTTPMethodView):
    @use_args({"val": fields.Int()}, location="form")
    async def post(self, request, args):
        return json(args)


app.add_route(EchoMethodViewUseArgs.as_view(), "/echo_method_view_use_args")


class EchoMethodViewUseKwargs(HTTPMethodView):
    @use_kwargs({"val": fields.Int()}, location="query")
    async def post(self, request, val):
        return json({"val": val})


app.add_route(EchoMethodViewUseKwargs.as_view(), "/echo_method_view_use_kwargs")

Parser without decorator with returning errors as JSON

from sanic import Sanic
from sanic.response import json

from webargs import fields
from webargs_sanic.sanicparser import parser, HandleValidationError

app = Sanic(__name__)

@app.route("/echo_view_args_validated/<value>", methods=["GET"])
async def echo_use_args_validated(request, args):
    parsed = await parser.parse(
        {"value": fields.Int(required=True, validate=lambda args: args["value"] > 42)}, request, location="view_args"
    )
    return json(parsed)


# Return validation errors as JSON
@app.exception(HandleValidationError)
async def handle_validation_error(request, err):
    return json({"errors": err.exc.messages}, status=422)

More complicated custom example

from sanic import Sanic
from sanic import response
from sanic import Blueprint

from webargs_sanic.sanicparser import use_kwargs

from some_CUSTOM_storage import InMemory

from webargs import fields
from webargs import validate

import marshmallow.fields
from validate_email import validate_email

#usually this should not be here, better to import ;)
#please check examples for more info
class Email(marshmallow.fields.Field):

    def __init__(self, *args, **kwargs):
        super(Email, self).__init__(*args, **kwargs)

    def _deserialize(self, value, attr, obj):
        value = value.strip().lower()
        if not validate_email(value):
            self.fail('validator_failed')
        return value

user_update = {
    'user_data': fields.Nested({
        'email': Email(),
        'password': fields.Str(validate=lambda value: len(value)>=8),
        'first_name': fields.Str(validate=lambda value: len(value)>=1),
        'last_name': fields.Str(validate=lambda value: len(value)>=1),
        'middle_name': fields.Str(),
        'gender': fields.Str(validate=validate.OneOf(["M", "F"])),
        'birth_date': fields.Date(),
    }),
    'user_id': fields.Str(required=True, validate=lambda x:len(x)==32),
}


blueprint = Blueprint('app')
storage = InMemory()


@blueprint.put('/user/')
@use_kwargs(user_update, location="json_or_form")
async def update_user(request, user_id, user_data):
    storage.update_or_404(user_id, user_data)
    return response.text('', status=204)

app = Sanic(__name__)
app.blueprint(blueprint, url_prefix='/')

For more examples and checking how to use custom validations (phones, emails, etc.) please check apps in Examples

Installing

It is easy to do from pip

pip install webargs-sanic

or from sources

git clone [email protected]:EndurantDevs/webtest-sanic.git
cd webtest-sanic
python setup.py install

Running the tests

Project uses common tests from webargs package. Thanks to Steven Loria for sharing tests in webargs v4.1.0. Most of tests are run by webtest via webtest-sanic. Some own tests get run via Sanic's TestClient.

To be sure everything is fine before installation from sources, just run:

pip -r requirements.txt

and then

python setup.py test

Or

pytest tests/

Authors

Endurant Developers Python Team

License

This project is licensed under the MIT License - see the LICENSE file for details

Owner
Endurant Devs
Endurant Devs
Asita is a web application framework for python.

What is Asita ? Asita is a web application framework for python. It is designed to be easy to use and be more easy for javascript users to use python

Mattéo 4 Nov 16, 2021
News search API developed for the purposes of the ColdCase Project.

Saxion - Cold Case - News Search API Setup Local – Linux/MacOS Make sure you have python 3.9 and pip 21 installed. This project uses a MySQL database,

Dimitar Rangelov 3 Jul 01, 2021
bottle.py is a fast and simple micro-framework for python web-applications.

Bottle: Python Web Framework Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module a

Bottle Micro Web Framework 7.8k Dec 31, 2022
Free and open source full-stack enterprise framework for agile development of secure database-driven web-based applications, written and programmable in Python.

Readme web2py is a free open source full-stack framework for rapid development of fast, scalable, secure and portable database-driven web-based applic

2k Dec 31, 2022
🦍 The Cloud-Native API Gateway

Kong or Kong API Gateway is a cloud-native, platform-agnostic, scalable API Gateway distinguished for its high performance and extensibility via plugi

Kong 33.8k Jan 09, 2023
A minimal, extensible, fast and productive API framework for Python 3.

molten A minimal, extensible, fast and productive API framework for Python 3. Changelog: https://moltenframework.com/changelog.html Community: https:/

Bogdan Popa 980 Nov 28, 2022
The little ASGI framework that shines. ?

✨ The little ASGI framework that shines. ✨ Documentation: https://www.starlette.io/ Community: https://discuss.encode.io/c/starlette Starlette Starlet

Encode 7.7k Jan 01, 2023
Goblet is an easy-to-use framework that enables developers to quickly spin up fully featured REST APIs with python on GCP

GOBLET Goblet is a framework for writing serverless rest apis in python in google cloud. It allows you to quickly create and deploy python apis backed

Austen 78 Dec 27, 2022
Phoenix LiveView but for Django

Reactor, a LiveView library for Django Reactor enables you to do something similar to Phoenix framework LiveView using Django Channels. What's in the

Eddy Ernesto del Valle Pino 526 Jan 02, 2023
A Simple Kivy Greeting App

SimpleGreetingApp A Simple Kivy Greeting App This is a very simple GUI App that receives a name text input from the user and returns a "Hello" greetin

Mariya 40 Dec 02, 2022
Serverless Python

Zappa - Serverless Python About Installation and Configuration Running the Initial Setup / Settings Basic Usage Initial Deployments Updates Rollback S

Rich Jones 11.9k Jan 01, 2023
WAZO REST API for the call management of the C4 infrastructure

wazo-router-calld wazo-router-calld provides REST API for the C4 infrastructure. Installing wazo-router-calld The server is already provided as a part

Wazo Platform 4 Dec 21, 2022
Asita is a web application framework for python based on express-js framework.

Asita is a web application framework for python. It is designed to be easy to use and be more easy for javascript users to use python frameworks because it is based on express-js framework.

Mattéo 4 Nov 16, 2021
A familiar HTTP Service Framework for Python.

Responder: a familiar HTTP Service Framework for Python Powered by Starlette. That async declaration is optional. View documentation. This gets you a

Taoufik 3.6k Dec 27, 2022
The comprehensive WSGI web application library.

Werkzeug werkzeug German noun: "tool". Etymology: werk ("work"), zeug ("stuff") Werkzeug is a comprehensive WSGI web application library. It began as

The Pallets Projects 6.2k Jan 01, 2023
REST API framework designed for human beings

Eve Eve is an open source Python REST API framework designed for human beings. It allows to effortlessly build and deploy highly customizable, fully f

eve 6.6k Jan 07, 2023
cirrina is an opinionated asynchronous web framework based on aiohttp

cirrina cirrina is an opinionated asynchronous web framework based on aiohttp. Features: HTTP Server Websocket Server JSON RPC Server Shared sessions

André Roth 32 Mar 05, 2022
Otter is framework for creating microservices in Flask like fassion using RPC communication via message queue.

Otter Framework for microservices. Overview Otter is framework for creating microservices in Flask like fassion using RPC communication via message qu

Volodymyr Biloshytskyi 4 Mar 23, 2022
Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.

Tornado Web Server Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. By using non-blocking ne

20.9k Jan 01, 2023
A tool for quickly creating REST/HATEOAS/Hypermedia APIs in python

ripozo Ripozo is a tool for building RESTful/HATEOAS/Hypermedia apis. It provides strong, simple, and fully qualified linking between resources, the a

Vertical Knowledge 198 Jan 07, 2023