Skip to content
This repository was archived by the owner on Jul 20, 2024. It is now read-only.
/ sanic-pydantic Public archive

A library for parsing and validating http requests for sanic web-framework using pydantic library

License

Notifications You must be signed in to change notification settings

nf1s/sanic-pydantic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

8091130 · May 12, 2022

History

87 Commits
May 12, 2022
May 12, 2022
May 12, 2022
May 12, 2022
May 12, 2022
May 28, 2020
Jul 20, 2020
May 28, 2020
Dec 10, 2021
Dec 10, 2021
May 12, 2022
Oct 14, 2021
May 12, 2022
May 12, 2022
May 24, 2020
Sep 27, 2020
May 28, 2020
Dec 10, 2021

Repository files navigation

Sanic Pyndatic

CircleCI codecov GitHub Pipenv locked Python version Downloads license

Description

A library for parsing and validating http requests for sanic web-framework using pydantic library

Full documentation here

Requirements

python >= 3.7

How to install

pip install sanic-pydantic

Dependencies

pydantic

Example

from sanic_pydantic import webargs

from sanic import Sanic
from sanic.response import json
from pydantic import BaseModel

app = Sanic("new app")


class PathModel(BaseModel):
    id: int


class QueryModel(BaseModel):
    name: str


class BodyModel(BaseModel):
    age: int


class HeadersModel(BaseModel):
    api_key: str = Field(alias="x-api-key")


@app.route("/get/<id:int>", methods=["GET"])
@webargs(path=PathModel, headers=HeadersModel)
def example_get_endpoint_params(request, id, **kwargs):
    response = json({"id":id})
    return response

@app.route("/get-request", methods=["GET"])
@webargs(query=QueryModel)
def example_get_endpoint(request, **kwargs):
    print(kwargs)
    response = json(kwargs)
    return response


@app.route("/post-request", methods=["POST"])
@webargs(query=QueryModel, body=BodyModel)
def example_post_endpoint(request, **kwargs):
    print(kwargs)
    response = json(kwargs)
    return response


@app.route("/async-get-request", methods=["GET"])
@webargs(query=QueryModel)
async def async_example_get_endpoint(request, **kwargs):
    print(kwargs)
    response = json(kwargs)
    return response


@app.route("/async-post-request", methods=["POST"])
@webargs(query=QueryModel, body=BodyModel)
async def async_example_post_endpoint(request, **kwargs):
    print(kwargs)
    response = json(kwargs)
    return response

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)