pymediate
API Reference

RequestHandler

API reference for the asynchronous and synchronous RequestHandler classes.

RequestHandler defines the callable that handles one Request type. The request's Request[ResponseT] declaration supplies the expected return type.

from abc import ABC, abstractmethod
from typing import Any

from pymediate import RequestHandler

class RequestHandler[RequestT](ABC):
    @abstractmethod
    async def __call__(self, request: RequestT) -> Any: ...
Type parameterMeaning
RequestTThe exact request class handled by this class

Definition-time validation

When Python defines a handler subclass, PyMediate checks that:

  • RequestT is a parameterized Request subclass;
  • the subclass defines __call__ with exactly one parameter besides self;
  • that parameter is annotated with the exact RequestT class;
  • the return annotation equals the response type declared by RequestT; and
  • __call__ is async def for pymediate.RequestHandler and plain def for pymediate.sync.RequestHandler.

Validation can raise InvalidRequestTypeError, InvalidHandlerSignatureError, ResponseTypeMismatchError, or HandlerAlreadyRegisteredError. The handler registry is process-wide and permits one request-handler class for each request type.

Example

from pymediate import RequestHandler


class PlaceOrderHandler(RequestHandler[PlaceOrder]):
    async def __call__(self, request: PlaceOrder) -> OrderReceipt:
        return OrderReceipt(
            order_id=42,
            summary=f"{request.quantity} × {request.item}",
        )

Use constructor parameters for the handler's dependencies. Register an instance of the handler with the service provider used by the mediator.

Introspection methods

These class methods are inherited by both variants:

MethodResult
get_request_type()The declared request class, or None on an unparameterized base
get_response_type()The inferred response class, or None when none is recorded
get_handler_for_request(request_type)The registered handler class; raises HandlerNotFoundError when absent

See also

  • Request — declares the response type
  • Mediator.send() — resolves and calls the handler
  • Handlers — dependencies, composition, and testing
  • Errors — validation and registration errors

On this page