Procedures
Define RPC procedures with types, validation, and async support.
Procedures
Procedures are Python functions decorated with @rpc. They receive validated parameters from the client and return a result.
Basic Definition
from pyrpc_core import rpc
@rpc
def add(a: int, b: int) -> int:
return a + bThe @model Decorator
The @model decorator is the preferred way to define complex data structures in pyRPC. It is a thin wrapper around Pydantic dataclasses that ensures your types are perfectly captured during introspection.
from pyrpc_core import model
@model
class User:
id: int
name: str
@rpc
def get_user(id: int) -> User:
return User(id=id, name="Paul Graham")When you run pyrpc codegen, this class is automatically synchronized as a TypeScript interface.
Universal Pydantic Validation
pyRPC uses Pydantic's TypeAdapter to automatically validate every parameter and return type. This means you get production-grade validation for free.
Return Type Validation
If you specify a return type hint, pyRPC validates the result before sending it to the client. If your function returns the wrong data type, pyRPC will raise an Internal Error (-32603) instead of sending invalid data to the client.
Sync vs Async
Procedures can be synchronous or asynchronous. pyRPC automatically detects and awaits coroutines.
@rpc
async def get_data_async(id: str):
await asyncio.sleep(1)
return {"id": id}Error Handling
If validation fails, pyRPC returns a standard JSON-RPC Invalid Params error (-32602) with a detailed data field explaining exactly which field failed and why.
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32602,
"message": "Validation failed",
"data": {
"field": "users.0.id",
"message": "Input should be a valid integer",
"type": "int_parsing"
}
}
}