Git Product home page Git Product logo

webargs-starlette's Introduction

webargs-starlette

PyPI version

marshmallow 3 compatible

code style: black

webargs-starlette is a library for declarative request parsing and validation with Starlette, built on top of webargs.

It has all the goodness of webargs, with some extra sugar for type annotations.

import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs_starlette import use_annotations

app = Starlette()


@app.route("/")
@use_annotations(location="query")
async def index(request, name: str = "World"):
    return JSONResponse({"Hello": name})


if __name__ == "__main__":
    uvicorn.run(app, port=5000)

# curl 'http://localhost:5000/'
# {"Hello": "World"}
# curl 'http://localhost:5000/?name=Ada'
# {"Hello": "Ada"}

Install

pip install -U webargs-starlette

Usage

Parser Usage

Use parser.parse to parse a Starlette Request with a dictionary of fields.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs import fields
from webargs_starlette import parser

app = Starlette()


@app.route("/")
async def homepage(request):
    args = {
        "name": fields.Str(required=True),
        "greeting": fields.Str(load_default="hello"),
    }
    parsed = await parser.parse(args, request)
    greeting = parsed["greeting"]
    name = parsed["name"]
    return JSONResponse({"message": f"{greeting} {name}"})

Decorators

Use the use_args decorator to inject the parsed arguments dictionary into the handler function. The following snippet is equivalent to the first example.

Important: Decorated functions MUST be coroutine functions.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs import fields
from webargs_starlette import use_args

app = Starlette()


@app.route("/")
@use_args(
    {"name": fields.Str(required=True), "greeting": fields.Str(load_default="hello")}
)
async def homepage(request, args):
    greeting = args["greeting"]
    name = args["name"]
    return JSONResponse({"message": f"{greeting} {name}"})

The use_kwargs decorator injects the parsed arguments as keyword arguments.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs import fields
from webargs_starlette import use_args

app = Starlette()


@app.route("/")
@use_kwargs(
    {"name": fields.Str(required=True), "greeting": fields.Str(load_default="hello")}
)
async def homepage(request, name, greeting):
    return JSONResponse({"message": f"{greeting} {name}"})

See decorator_example.py for a more complete example of use_args and use_kwargs usage.

Error Handling

When validation fails, the parser will raise a WebargsHTTPException, which is the same as Starlette's HTTPException with the addition of of the messages (validation messages), headers , exception (underlying exception), and schema (marshmallow Schema) attributes.

You can use a custom exception handler to return the error messages as JSON.

from starlette.responses import JSONResponse
from webargs_starlette import WebargsHTTPException


@app.exception_handler(WebargsHTTPException)
async def http_exception(request, exc):
    return JSONResponse(exc.messages, status_code=exc.status_code, headers=exc.headers)

Annotations

The use_annotations decorator allows you to parse request objects using type annotations.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs_starlette import use_annotations

app = Starlette()


@app.route("/")
@use_annotations(location="query")
async def welcome(request, name: str = "Friend"):
    return JSONResponse({"message": f"Welcome, {name}!"})


# curl 'http://localhost:5000/'.
# {"message":"Welcome, Friend!"}
# curl 'http://localhost:5000/?name=Ada'.
# {"message":"Welcome, Ada!"}

Any annotated argument that doesn't have a default value will be required. For example, if we remove the default for name in the above example, an 422 error response is returned if ?name isn't passed.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs_starlette import use_annotations, WebargsHTTPException

app = Starlette()


@app.route("/")
@use_annotations(location="query")
async def welcome(request, name: str):
    return JSONResponse({"message": f"Welcome, {name}!"})


@app.exception_handler(WebargsHTTPException)
async def http_exception(request, exc):
    return JSONResponse(exc.messages, status_code=exc.status_code, headers=exc.headers)


# curl "http://localhost:5000/"
# {"name":["Missing data for required field."]}

Arguments may also be annotated with Field instances when you need more control. For example, you may want to add a validator.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from webargs import fields
from marshmallow import validate
from webargs_starlette import use_annotations, WebargsHTTPException

app = Starlette()


@app.route("/")
@use_annotations(location="query")
async def welcome(request, name: fields.Str(validate=validate.Length(min=2))):
    return JSONResponse({"message": f"Welcome, {name}!"})


@app.exception_handler(WebargsHTTPException)
async def http_exception(request, exc):
    return JSONResponse(exc.messages, status_code=exc.status_code, headers=exc.headers)


# curl "http://localhost:5000/?name=A"
# {"name":["Shorter than minimum length 2."]}

HTTPEndpoint methods may also be decorated with use_annotations.

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.endpoints import HTTPEndpoint
from webargs_starlette import use_annotations

app = Starlette()


@app.route("/")
class WelcomeEndpoint(HTTPEndpoint):
    @use_annotations(location="query")
    async def get(self, request, name: str = "World"):
        return JSONResponse({"message": f"Welcome, {name}!"})

See annotation_example.py for a more complete example of use_annotations usage.

More

For more information on how to use webargs, see the webargs documentation.

License

MIT licensed. See the LICENSE file for more details.

webargs-starlette's People

Contributors

dependabot-preview[bot] avatar dmitryburnaev avatar sloria avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

webargs-starlette's Issues

load_from and data_key not working

If I use data_key or load_from in my schema the value gets dropped during parsing.
Is there any way to have the value renamed during parsing?

use_kwargs not working with version 2.0.0

This works with version 1.2.1

class AirportsEndpoint(HTTPEndpoint):
    @use_kwargs(QuerySchema)
    async def get(self, request, **kwargs):
        log.info(f"get airports - kwargs: {kwargs}")
        airports = await query_airports(**kwargs)
        airports_json = AirportSchema().dump(airports, many=True)
        return JSONResponse(airports_json)

But with version 2.0.0 kwargs are empty. It works when it's not a function in a class

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.