Controller
Controller (GRASP)
"Assign the responsibility for handling a system event to a class that represents one of: the overall system, a root object, a device, or a use-case scenario within which the system event occurs." — Craig Larman, Applying UML and Patterns
"Skinny controllers, fat models." — Rails community, 2005. A universal principle even outside Rails.
Core idea
A Controller is a class that takes an external event (HTTP request, CLI command, click, message) and passes it on to the business logic. It is thin: it parses the input, calls the use case, formats the output. No business rules inside.
Why it matters
| Without Controller | With Controller |
|---|---|
| Business logic mixed with HTTP / CLI / UI | Business logic does not know about delivery |
| The same feature for HTTP and CLI is duplicated | One use case, many controllers |
| Testing the business logic needs an HTTP server | Testing the business logic is service.execute(...) |
| Moving from Flask to FastAPI = rewriting half the code | Only the controller layer changes |
| HTTP status codes live next to formulas | HTTP status codes live in the controller, business in the service |
| JSON parsing lives inside the price calculator | Parsing in the controller, computation in the calculator |
Litmus test: if your business logic touches
request.json,response.status,print(), orsys.argv, that is not business logic. That is a fat controller.
Two kinds of Controller per Larman
1. Facade Controller (a facade for the system)
Represents the system as a whole — one entry point for all events.
class OrderSystem:
def __init__(self, services...):
self._checkout = CheckoutService(...)
self._refund = RefundService(...)
self._tracking = TrackingService(...)
def handle_checkout(self, order_data) -> Result: ...
def handle_refund(self, refund_data) -> Result: ...
def handle_tracking(self, tracking_id) -> Status: ...
Useful for simple systems with a small number of use cases. Becomes bulky when the use cases grow.
2. Use Case Controller (one per scenario)
A separate class for each use case:
class CheckoutController:
def __init__(self, service: CheckoutService):
self._service = service
def handle(self, request: dict) -> dict: ...
class RefundController:
def __init__(self, service: RefundService):
self._service = service
def handle(self, request: dict) -> dict: ...
This is the standard in web frameworks: one view or handler per endpoint. More classes, but each is about one thing (SRP-friendly).
Anatomy of a thin Controller
A controller should do exactly four things:
def handle_checkout(request: HttpRequest, service: CheckoutService) -> HttpResponse:
# 1. Parse the INPUT from the external format into the domain
try:
cmd = CheckoutCommand(
user_id=request.json["user_id"],
items=request.json["items"],
card_token=request.json["card_token"],
)
except (KeyError, TypeError) as e:
return HttpResponse(400, {"error": f"invalid request: {e}"})
# 2. Delegate to the use case
try:
result = service.execute(cmd)
except ValidationError as e:
return HttpResponse(400, {"error": str(e)})
except PaymentDeclined as e:
return HttpResponse(402, {"error": str(e)})
except InsufficientStock as e:
return HttpResponse(409, {"error": str(e)})
# 3. Format the OUTPUT
return HttpResponse(201, {
"transaction_id": result.transaction_id,
"total": result.total,
})
What does not happen here:
- No price formulas.
- No
INSERT INTO. - No calls to the payment gateway.
- No email sending.
All of that lives in service.execute(cmd).
The power of Controller: one use case, many controllers
That is the main advantage of a dedicated Controller layer:
class RegisterUserService:
"""Use case. Does not know about HTTP, CLI, or tests."""
def execute(self, email: str, password: str, age: int) -> User: ...
# --- HTTP Controller ---
def http_register(request: dict, service: RegisterUserService) -> dict:
try:
user = service.execute(
email=request["email"],
password=request["password"],
age=request["age"],
)
return {"status": 201, "user_id": user.id}
except ValueError as e:
return {"status": 400, "error": str(e)}
# --- CLI Controller ---
def cli_register(args: list[str], service: RegisterUserService) -> int:
try:
user = service.execute(
email=args[0],
password=args[1],
age=int(args[2]),
)
print(f"Registered: {user.email}")
return 0
except ValueError as e:
print(f"Error: {e}", file=sys.stderr)
return 1
# --- Test "Controller" (called from a test) ---
def test_register():
service = RegisterUserService(repo=FakeRepo(), hasher=FakeHasher())
user = service.execute("[email protected]", "secret123", 25)
assert user.email == "[email protected]"
The same RegisterUserService serves:
- the production HTTP API,
- an internal CLI for admins,
- a test run with no framework at all.
Each controller knows only its own input/output format. The service knows only the domain. No duplication.
Connection to Hexagonal Architecture
A Controller is a primary (driving) adapter in Hexagonal Architecture:
┌──────────────────────────────┐
│ DOMAIN (use cases) │
│ RegisterUserService │
└──────────┬───────────────────┘
│
┌─────────────────────┴─────────────────────┐
│ Primary Adapters (Controllers — drive) │
│ │
│ HttpController, CliController, │ ← call into the domain
│ WebSocketController, KafkaConsumer │
└───────────────────────────────────────────┘
▼
┌──────────────────────────────────────────┐
│ Secondary Adapters (Repositories, etc.) │ ← called by the domain
│ │
│ PostgresUserRepo, StripeGateway, ... │
└──────────────────────────────────────────┘
- Primary (driving) — controllers that start a use case.
- Secondary (driven) — repositories and gateways the use case calls.
- Domain — in the middle, imports nothing from outside.
That is how the DIP idea expands into an architectural shape.
DTO / Command — how to parse input
Instead of passing a "raw dict" into the service, use a Command object (an immutable DTO):
@dataclass(frozen=True)
class RegisterUserCommand:
email: str
password: str
age: int
class RegisterUserService:
def execute(self, cmd: RegisterUserCommand) -> User: ...
Advantages:
- Typed — the IDE and mypy check it.
- Immune to input format changes — a new HTTP field changes the controller's parsing, not the service.
- Self-documenting — you can see what the service expects.
The controller does: HTTP → Command → service → Result → HTTP. The domain works with Command and Result, not with HTTP details.
Anti-patterns
1. Fat Controller — business logic in the controller
@app.post("/checkout")
def checkout(request):
items = request.json["items"]
total = sum(i["price"] * i["qty"] for i in items) # ← business!
if total > 1000: total *= 0.9 # ← business!
conn.execute("INSERT INTO orders ...") # ← infrastructure!
return {"total": total}
This is not a controller. It is a god view. Move the business logic into a service.
2. The domain knows about HTTP
class CheckoutService:
def execute(self, request: HttpRequest): # ← HttpRequest inside the domain!
...
The domain should not know about HttpRequest. If tomorrow we want a CLI, we rewrite everything. Use a Command / DTO instead.
3. The controller returns a domain object to the client
@app.post("/users")
def create_user(request):
user = service.execute(...)
return user # ← returning User directly
The domain User may contain hashed_password, internal_id, an audit log, and more. Not all of it should appear in the API response. Translate it:
return {
"id": user.id,
"email": user.email,
# password_hash, audit_log — do NOT return
}
This is DTO mapping. A separate response DTO is fine.
4. One controller for ten use cases
class UserController:
def handle(self, action, data):
if action == "register": ...
elif action == "login": ...
elif action == "reset_password": ...
elif action == "delete_account": ...
elif action == "export_data": ...
if/elif on the action is an anti-OCP pattern. Split into separate handlers (RegisterController, LoginController).
5. A controller without a service
@app.post("/orders")
def create_order(request):
# 100 lines of logic right here
...
If the controller is over 20-30 lines, it is a signal you skipped the use-case service. Extract it.
6. A controller for every small class
class OrderItemController: ...
class OrderItemValidationController: ...
class OrderItemPricingController: ...
A Controller is the entry point of a use case, not "a wrapper around every class". One controller per scenario, not "one controller per model".
What a Controller does, and does not do
| Does | Does NOT |
|---|---|
| Parse JSON / args / form | Run business validation (domain rules) |
| Check input format (JSON schema) | Check business invariants |
| Convert to Command / DTO | Talk to the DB |
Call service.execute(cmd) |
Call external services |
| Map exceptions to HTTP codes | Send email, take payments, write files |
| Format the response (JSON, HTML, plain) | Everything above belongs in the service |
Relationship to other principles
| Principle | How it relates |
|---|---|
| SRP | Controller has one role (delivery), service has another (business) |
| DIP | Controller receives a service as a dependency, that is DI |
| OCP | A new delivery channel (gRPC) is a new controller, the domain stays |
| Composition Root | The controller is instantiated in main / app_factory |
| SoC | Delivery (HTTP / CLI) and logic are separate layers |
| Information Expert | Controller is the expert on request format, service is the expert on business |
Rules of thumb
- A controller is thin. Over 20-30 lines is a sign to extract a service.
- No
request.jsonorprint()inside the service. Services work with Command / DTO. - One controller per use case. Not "UserController with 10 methods", but
RegisterController,LoginController. - Exceptions to HTTP codes mapping lives in the controller, not in the service. Services throw domain exceptions.
- Response DTO is not the domain object. Use a separate class (or dict) for the response.
- The service is testable without the controller. That is the test of correct isolation.
main()creates the controller and injects the service. Composition Root.
One-line summary
A Controller is a thin "outside-to-middle" layer. Parse the input, call a use case, format the output. The business sits below it. If the controller contains the discount formula, that is not a controller, that is an architecture bug.