All Projects → sloria → webargs-starlette

sloria / webargs-starlette

Licence: MIT License
Declarative request parsing and validation for Starlette with webargs

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to webargs-starlette

Graphql Go Tools
Tools to write high performance GraphQL applications using Go/Golang.
Stars: ✭ 96 (+166.67%)
Mutual labels:  validation, parsing
async-asgi-testclient
A framework-agnostic library for testing ASGI web applications
Stars: ✭ 123 (+241.67%)
Mutual labels:  asgi, starlette
Aiohttp Apispec
Build and document REST APIs with aiohttp and apispec
Stars: ✭ 172 (+377.78%)
Mutual labels:  validation, marshmallow
Pydantic
Data parsing and validation using Python type hints
Stars: ✭ 8,362 (+23127.78%)
Mutual labels:  validation, parsing
spectree
API spec validator and OpenAPI document generator for Python web frameworks.
Stars: ✭ 190 (+427.78%)
Mutual labels:  asgi, starlette
Govalidator
Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.
Stars: ✭ 969 (+2591.67%)
Mutual labels:  validation, request
mongox
Familiar async Python MongoDB ODM
Stars: ✭ 113 (+213.89%)
Mutual labels:  asgi, starlette
fefe
Validate, sanitize and transform values with proper TypeScript types and zero dependencies.
Stars: ✭ 34 (-5.56%)
Mutual labels:  validation, parsing
arel
Lightweight browser hot reload for Python ASGI web apps
Stars: ✭ 69 (+91.67%)
Mutual labels:  asgi, starlette
inboard
🚢 Docker images and utilities to power your Python APIs and help you ship faster. With support for Uvicorn, Gunicorn, Starlette, and FastAPI.
Stars: ✭ 106 (+194.44%)
Mutual labels:  asgi, starlette
Firely Net Sdk
The official Firely .NET SDK for HL7 FHIR
Stars: ✭ 560 (+1455.56%)
Mutual labels:  validation, parsing
serverless-mangum-examples
Example ASGI applications and Serverless Framework configurations using Mangum
Stars: ✭ 26 (-27.78%)
Mutual labels:  asgi, starlette
Phonenumberkit
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.
Stars: ✭ 4,362 (+12016.67%)
Mutual labels:  validation, parsing
Webargs
A friendly library for parsing HTTP request arguments, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, webapp2, Falcon, and aiohttp.
Stars: ✭ 1,145 (+3080.56%)
Mutual labels:  validation, marshmallow
apple-receipt
Apple InAppPurchase Receipt - Models, Parser, Validator
Stars: ✭ 25 (-30.56%)
Mutual labels:  validation, parsing
Marshmallow Jsonapi
JSON API 1.0 (https://jsonapi.org/) formatting with marshmallow
Stars: ✭ 203 (+463.89%)
Mutual labels:  validation, marshmallow
full-stack-flask-couchdb
Full stack, modern web application generator. Using Flask, CouchDB as database, Docker, Swagger, automatic HTTPS and more.
Stars: ✭ 28 (-22.22%)
Mutual labels:  marshmallow, webargs
Idne
💎 Codeforces submit command line tool
Stars: ✭ 65 (+80.56%)
Mutual labels:  parsing, request
starlite
Light, Flexible and Extensible ASGI API framework
Stars: ✭ 1,525 (+4136.11%)
Mutual labels:  asgi, starlette
fastapi-zeit-now
A simple example of deploying FastAPI as a Zeit Serverless Function
Stars: ✭ 24 (-33.33%)
Mutual labels:  asgi, starlette

webargs-starlette

PyPI version Build status 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(missing="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(missing="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(missing="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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].