Handlers

Overview

Handlers are functions responsible for handling received requests. They are defined through the @get, @post, @put, @patch, @delete and @websocket decorators.

Handlers must receive, at least, the request object as the first parameter. It is not needed to annotate the request parameter, but it should be the first parameter.

import structlog
from asgikit import Request
from zayt.web import get, post

logger = structlog.get_logger(__name__)


@get
async def index(request: Request):
    await request.respond_text("application root")


@post("send")
async def handle_data(request: Request):
    content = await request.body.read_json()
    logger.info("request body: ", content=repr(content))
    await request.redirect("/")

Note

Defining a path on @get @post etc... is optional and defaults to an empty string.

Handler function can be defined with path parameters, which can be retrieved from the property asgikit.Request.path_params:

from zayt.web import Request, get


@get("/{path_param}")
def handler(request: Request):
    path_param = request.path_params["path_param"]

The routing section provides more information about path parameters

Responses

Handlers do not return a response. Instead, they call one of the respond_* methods of the asgikit.Request object in order to respond to the request.

from asgikit import Request
from zayt.web import get


@get
async def handler(request: Request):
    await request.respond_json({"data": "The response"})

The respond_* methods on the asgikit.Request class are actually proxies for the methods in the asgikit.Response class.

Dependencies

Handler functions can receive services as parameters that will be injected when the handler is called.

from zayt.di import service
from zayt.web import get


@service
class MyService:
    pass


@get
def my_handler(request, my_service: MyService):
    ...

Handler parameters can be annotated with Inject in order to customize the dependency:

from typing import Annotated
from zayt.di import Inject, service
from zayt.web import get


@service(name="named-service")
class MyService:
    pass


@get
def my_handler(
    request,
    my_service: Annotated[MyService, Inject(name="named-service")]
):
    ...

Request Data

From the request object, you can retrieve data like the request path, method, headers, etc.

from http import HTTPMethod, HTTPStatus
from asgikit import Request, WebSocket
from zayt.web import get, websocket


@get
async def handler(request: Request):
    assert request.method == HTTPMethod.GET
    assert request.path == "/"
    body = await request.json()
    await request.respond_json({"status": HTTPStatus.OK})