Controller
Controllers are the HTTP interface layer of Tasteful flavors. They handle incoming HTTP requests, delegate business logic to services, and return appropriate responses. Controllers act as the entry point for all HTTP interactions with your application.What is a Controller?
A Controller in Tasteful is a class that inherits fromBaseController and defines HTTP endpoints using route decorators. Controllers are responsible for:
- HTTP Request Handling: Processing incoming requests and extracting data
- Route Definition: Mapping URLs to specific handler methods
- Response Formatting: Returning properly formatted HTTP responses
- Service Orchestration: Delegating business logic to services
- Input Validation: Basic request validation (detailed validation happens in services)
Core Concepts
BaseController Foundation
All controllers inherit fromBaseController, which provides:
BaseController:
- Automatic Router Creation: Creates a FastAPI
APIRouterinstance - URL Prefixing: All routes are prefixed with the specified path
- Tag Organization: Groups endpoints for API documentation
- Endpoint Registration: Automatically registers decorated methods as routes
Route Decorators
Tasteful provides HTTP method decorators that mirror FastAPI’s functionality:Implementation
Basic Controller Implementation
Here’s a complete example of a controller implementation:Advanced Patterns
Multiple Service Dependencies
Controllers can depend on multiple services:Custom Route Parameters
You can pass additional FastAPI parameters to route decorators:Integration with Other Components
Controller-Service Relationship
Controllers should always delegate business logic to services:Dependency Injection
Controllers receive their dependencies through constructor injection, managed automatically by Tasteful’s dependency injection system:Best Practices
Do’s
- Keep controllers thin - Delegate all business logic to services
- Use meaningful HTTP status codes - Return appropriate status codes for different scenarios
- Handle errors gracefully - Convert service exceptions to appropriate HTTP responses
- Use type hints - Provide clear type annotations for better documentation and IDE support
- Follow RESTful conventions - Use standard HTTP methods and URL patterns
- Document endpoints - Use docstrings and FastAPI parameters for API documentation
Don’ts
- Don’t put business logic in controllers - Controllers should only handle HTTP concerns
- Don’t access repositories directly - Always go through services
- Don’t handle complex validation - Let services handle detailed validation
- Don’t manage transactions - Leave transaction management to services
- Don’t hardcode responses - Use proper response models and status codes