Controller Structure
Controllers are simple structs with static methods that handle specific routes:src/infrastructure/http/controllers/auth_controller.rs
Controller Responsibilities
Controllers should be thin and focused on HTTP concerns:- Extract request data - Parse JSON, query params, path params
- Validate input - Use
ValidatedJsonfor automatic validation - Call services - Delegate business logic to application services
- Return responses - Map results to appropriate HTTP status codes
Request Handling Patterns
Automatic Validation
UseValidatedJson to automatically validate DTOs before processing:
src/infrastructure/http/controllers/test_item_controller.rs
ValidatedJson extractor:
- Automatically parses JSON from request body
- Runs validation rules defined on the DTO
- Returns
400 Bad Requestif validation fails - Extracts the validated DTO with
req.0
Path Parameters
Extract dynamic URL segments:src/infrastructure/http/controllers/test_item_controller.rs
Query Parameters
Handle pagination and filtering with query params:src/infrastructure/http/controllers/user_controller.rs
Authentication & Authorization
Use extractors to enforce authentication requirements:Authenticated User
src/infrastructure/http/controllers/user_controller.rs
AuthUser extractor:
- Verifies the JWT token
- Returns
401 Unauthorizedif token is invalid - Provides access to user claims via
auth.0
Admin-Only Endpoints
src/infrastructure/http/controllers/auth_controller.rs
AdminUser extractor:
- Verifies JWT token AND admin role
- Returns
403 Forbiddenif user is not an admin
Authorization Checks
Implement custom authorization logic when needed:src/infrastructure/http/controllers/user_controller.rs
HTTP Status Codes
Return appropriate status codes based on the operation:Service Injection
Services are injected via Actix’s dependency injection:Services must be registered in your application state during setup. See Services for configuration details.
Error Handling
The? operator automatically converts errors to HTTP responses:
src/infrastructure/http/controllers/test_item_controller.rs
service.update() returns an error, it’s automatically converted to the appropriate HTTP response.
Complete CRUD Controller Example
src/infrastructure/http/controllers/test_item_controller.rs
Best Practices
Next Steps
- Learn about Services for business logic
- Understand DTOs for request/response validation
- Explore authentication extractors