API schema generation and input validation for aiohttp.web.
Install from PyPI:
pip install aiohttp-apischema
Install requirement and launch tests:
pip install -r requirements-dev.txt pytest
First create a SchemaGenerator instance:
from aiohttp_apischema import SchemaGenerator
SCHEMA = SchemaGenerator()
Then decorate endpoint handlers which should be included in the schema:
from aiohttp_apischema import APIResponse
@SCHEMA.api()
async def foo(request: web.Request) -> APIResponse[list[str], Literal[200]]:
return APIResponse(["foo"])
Or for Class Based Views:
@SCHEMA.api_view()
class Handler(web.View):
async def get(self) -> APIResponse[int, Literal[200]] | APIResponse[None, Literal[404]]:
bar_id = int(self.request.match_info["id"])
if bar_id == 1:
return APIResponse(42)
return APIResponse[None, Literal[404]](None, status=404)
Then call the setup method when building your app:
app = web.Application()
app.router.add_get("/foo", foo)
app.router.add_view(r"/bar/{id:\d+}", Handler)
SCHEMA.setup(app)
You can now view the docs under the /swagger/ path.
Validation of the request body is achieved by adding a positional parameter:
async def handler(request: web.Request, body: dict[int, str]) -> APIResponse[int, Literal[200]]:
# body has been validated, so we can be sure the keys are int now.
return APIResponse(sum(body.keys()))
aiohttp_apischema
is offered under the Apache 2 license.