/protean:api-endpointfrom protean
Defines FastAPI API endpoints for Protean applications. Endpoints are thin adapters that translate HTTP requests into domain commands and hand them off via domain.process(). Contains no business logic.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Protean ships a FastAPI integration in protean.integrations.fastapi. FastAPI
comes with the server extra, so install it first:
pip install "protean[server]"
The integration gives you two pieces. DomainContextMiddleware pushes the
domain context for each request, so current_domain works inside an endpoint.
register_exception_handlers turns six exceptions, five from Protean and
Python's ValueError, into HTTP responses. They are listed under
Status codes. An endpoint needs no try/except for those.
Any other exception gives a plain 500. One example is TooManyObjectsError,
which repository.find_by raises when more than one row matches.
The endpoints below submit commands to this aggregate and handler. The
handler loads an existing order with repository.get, which raises
ObjectNotFoundError for an unknown id.
from protean import current_domain
from protean.exceptions import InvalidStateError
@domain.aggregate
class Order:
order_id = Identifier(identifier=True)
customer_id = String(required=True)
total_amount = Decimal(precision=19, scale=4, min_value=0)
status = String(default="placed")
cancel_reason = String()
def cancel(self, reason: str) -> None:
if self.status == "cancelled":
raise InvalidStateError("Order is already cancelled")
self.status = "cancelled"
self.cancel_reason = reason
@domain.command(part_of=Order)
class PlaceOrder:
order_id = Identifier(required=True)
customer_id = String(required=True, max_length=50)
total_amount = Decimal(precision=19, scale=4, required=True, min_value=0)
@domain.command(part_of=Order)
class CancelOrder:
order_id = Identifier(required=True)
reason = String(required=True)
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def place(self, command: PlaceOrder) -> str:
order = Order(
order_id=command.order_id,
customer_id=command.customer_id,
total_amount=command.total_amount,
)
current_domain.repository_for(Order).add(order)
return order.order_id
@handle(CancelOrder)
def cancel(self, command: CancelOrder) -> str:
order = current_domain.repository_for(Order).get(command.order_id)
order.cancel(command.reason)
current_domain.repository_for(Order).add(order)
return order.order_id
Put endpoints on an APIRouter. Each endpoint builds a command from the
request and passes it to current_domain.process(..., asynchronous=False).
from decimal import Decimal as D
from fastapi import APIRouter
from pydantic import BaseModel
class PlaceOrderRequest(BaseModel):
order_id: str
customer_id: str
total_amount: D
router = APIRouter(prefix="/orders", tags=["orders"])
@router.post("", status_code=201)
def place_order(body: PlaceOrderRequest):
command = PlaceOrder(
order_id=body.order_id,
customer_id=body.customer_id,
total_amount=body.total_amount,
)
order_id = current_domain.process(command, asynchronous=False)
return {"order_id": order_id, "status": "placed"}
Build the app in one function. It adds the middleware, registers the exception handlers, and includes your routers. Pass it an initialized domain.
from fastapi import FastAPI
from protean.integrations.fastapi import (
DomainContextMiddleware,
register_exception_handlers,
)
def create_app(domain: Domain) -> FastAPI:
app = FastAPI()
app.add_middleware(DomainContextMiddleware, route_domain_map={"/": domain})
register_exception_handlers(app)
app.include_router(router)
return app
route_domain_map={"/": domain} sends every request to one domain. An app
with several bounded contexts maps one URL prefix to each domain instead.
To serve it, initialize the domain and hand the app to uvicorn:
# fragment
import uvicorn
domain.init()
uvicorn.run(create_app(domain), host="127.0.0.1", port=8000)
query and projection skills.def: current_domain.process(..., asynchronous=False) is a blocking call. FastAPI runs a def endpoint in its thread pool, which keeps that call off the event loop. The domain context from the middleware still reaches the endpoint there. An async def endpoint that calls process() blocks every other request while it runs.DomainContextMiddleware and call register_exception_handlers(app) in the app factory. Do not write your own.current_domain.process(): Never call a handler directly. Import current_domain from protean.asynchronous=False: The endpoint then gets the handler's return value, and a domain error such as a missing aggregate is raised inside the request, where the exception handlers can turn it into a 404 or 409.register_exception_handlers maps these exceptions, and only these, to a
response. Any other exception gives a plain-text 500.
| Exception | Status | Body |
|---|---|---|
ValidationError | 400 | {"error": {"<field>": ["<message>", ...]}} |
InvalidDataError | 400 | {"error": {"<field>": ["<message>", ...]}} |
ValueError | 400 | {"error": "<message>"} |
ObjectNotFoundError | 404 | {"error": "<message>"} |
InvalidStateError | 409 | {"error": "<message>"} |
InvalidOperationError | 422 | {"error": "<message>"} |
A ValidationError also comes from the repository: adding an aggregate whose
id is already stored gives a 400 keyed by the id field.
When a domain context is active, each body in the table also carries
correlation_id. It
matches the response's X-Correlation-ID header. The middleware pushes a
domain context only for paths that match one of its mapped prefixes, so a
request outside them has no correlation_id in its error body.
Two different things can return 422:
InvalidOperationError gives {"error": "<message>"}.{"detail": [...]}, with no
error key and no correlation_id. Pydantic converts some values in its
default mode, so "5" and true pass a float field as 5.0 and 1.0.
Use Field(strict=True) on a field that must reject them.A value that passes the Pydantic model but breaks a command field rule, such
as a customer_id longer than max_length=50, gives Protean's 400.
| Pattern | HTTP Method | Example | Command Source |
|---|---|---|---|
| Create resource | POST | POST /orders | Body |
| Action on resource | PUT | PUT /orders/{id}/cancel | Path + Body |
| Action without body | PUT | PUT /shipments/{id}/deliver | Path only |
class CancelOrderRequest(BaseModel):
reason: str
@router.put("/{order_id}/cancel")
def cancel_order(order_id: str, body: CancelOrderRequest):
command = CancelOrder(order_id=order_id, reason=body.reason)
current_domain.process(command, asynchronous=False)
return {"order_id": order_id, "status": "cancelled"}
The order id comes from the path and the reason from the body. An unknown id gives a 404, and cancelling twice gives a 409, with no error handling in the endpoint.
current_domain.process(command, asynchronous=False) runs the handler during
the request and returns the handler's result. current_domain.process(command)
uses the domain's command_processing setting, which is "async" by default.
It stores the command and returns its position in the event store, and the
server's engine runs the handler later.
Use asynchronous=False when the endpoint needs the handler's result, or
needs a missing aggregate to become a 404. With async processing the endpoint
returns success even if the handler later fails.
# fragment
# Wrong! Business logic belongs in the aggregate
@router.post("")
def place_order(body: PlaceOrderRequest):
if body.total_amount <= 0: # Business rule in the endpoint!
return JSONResponse(status_code=400, content={"error": "Invalid amount"})
Instead: let the command and the aggregate enforce the rule. The endpoint only builds the command.
# fragment
# Wrong! The endpoint persists the aggregate itself
@router.post("")
def place_order(body: PlaceOrderRequest):
order = Order(order_id=body.order_id, customer_id=body.customer_id)
current_domain.repository_for(Order).add(order) # Direct repo access!
Instead: build a command and pass it to current_domain.process(). The handler saves the aggregate.
async def endpoint that calls process()# fragment
# Wrong! process() blocks the event loop for every other request
@router.post("")
async def place_order(body: PlaceOrderRequest):
current_domain.process(PlaceOrder(**body.model_dump()), asynchronous=False)
Instead: write the endpoint as plain def.
# fragment
# Wrong! The integration already does this, and adds correlation IDs
@app.middleware("http")
async def domain_context_middleware(request, call_next):
with domain.domain_context():
return await call_next(request)
Instead: add DomainContextMiddleware and call register_exception_handlers(app) in the app factory.
# fragment
# Wrong! Never bypass domain.process()
@router.post("")
def place_order(body: PlaceOrderRequest):
OrderCommandHandler().place(command) # Skips enrichment and the event store!
Instead: always use current_domain.process(command, asynchronous=False).
TestClientcreate_app factory and a full router for one aggregatecommand: Commands are what endpoints constructcommand-handler: Command handlers process the commands that endpoints submitaggregate: The target of commands submitted through endpointscheck and resolve what it reportsassets/api_endpoint_complete_router.py (opens in a new tab)assets/api_endpoint_path_params.py (opens in a new tab)assets/api_endpoint_simple.py (opens in a new tab)assets/api_endpoint_with_pydantic.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/request-validation.md (opens in a new tab)references/response-patterns.md (opens in a new tab)references/testing-endpoints.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub proteanhq/protean --plugin protean39 skills in this plugin
/add-commandAdd a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar".Other plugins' skills for the same job