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 parameter | Meaning |
|---|---|
RequestT | The exact request class handled by this class |
Definition-time validation
When Python defines a handler subclass, PyMediate checks that:
RequestTis a parameterizedRequestsubclass;- the subclass defines
__call__with exactly one parameter besidesself; - that parameter is annotated with the exact
RequestTclass; - the return annotation equals the response type declared by
RequestT; and __call__isasync defforpymediate.RequestHandlerand plaindefforpymediate.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:
| Method | Result |
|---|---|
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