Skip to content

Decorators

The two decorators that make up the entire user-facing surface for defining services.

fastgrpc.decorators.service

service(cls: T) -> T

Mark a class as a gRPC service. Registered into the global registry.

Source code in src/fastgrpc/decorators.py
def service(cls: T) -> T:
    """Mark a class as a gRPC service. Registered into the global registry."""
    setattr(cls, _SERVICE_MARKER, True)
    _registry.append(cls)
    return cls

fastgrpc.decorators.rpc

rpc(fn: F) -> F

Mark an async method as an RPC handler.

Source code in src/fastgrpc/decorators.py
def rpc(fn: F) -> F:
    """Mark an async method as an RPC handler."""
    setattr(fn, _RPC_MARKER, True)
    return fn

Usage

from dataclasses import dataclass
from fastgrpc import rpc, service

@dataclass
class User:
    id: int
    name: str

@service
class UserService:
    @rpc
    async def get_user(self, user_id: int) -> User:
        return User(id=user_id, name="Ashesh")

Constraints

  • Service classes must have a no-argument __init__ (fastgrpc instantiates them as cls())
  • RPC method names must be unique within a service
  • Service class names must be unique across the entire registry — see Multi-file projects
  • All @rpc methods on a class must share a sync/async style — see Async vs sync

Type hint requirements

Every parameter and the return value must be annotated. Supported types:

Python Protobuf
int int64
float double
str string
bool bool
bytes bytes
list[T] repeated T
dict[str, T] map<string, T>
T \| None optional T
@dataclass nested message
AsyncIterator[T] stream T (async)
Iterator[T] stream T (sync)