Your FastAPI module for managing tasks is well-structured and follows common best practices. However, there are several areas where you can enhance functionality, improve code quality, and ensure better maintainability and security. Below, I'll provide a detailed review of your code along with suggestions for improvement.
1. Imports and Dependencies
Issue: Missing Imports
User Model: The User model is referenced in the route dependencies (current_user: User = Depends(get_current_user)) but isn't imported. Ensure you import it at the beginning of your module.
Recommendation:
from models.user import User # Add this import
Improvement: Organize Imports
- Group standard library imports, third-party imports, and local imports separately for better readability.
Example:
from datetime import date
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Depends, status
from pydantic import BaseModel
from models.task import Task
from models.user import User
from models.change import Change
from services.task_service import TaskService
from utils.dependencies import get_current_user, get_current_admin
2. Type Annotations and Models
Issue: Response Models and Request Bodies
- For
create_task and update_task, you're using function parameters directly as inputs. It's more scalable and cleaner to define Pydantic models for request bodies, especially as the number of parameters grows.
Recommendation: Define Pydantic Models for Requests
class TaskCreate(BaseModel):
title: str
description: Optional[str] = None
expiration_date: Optional[date] = None
status_id: Optional[int] = 1 # Default to 'Por hacer'
class TaskUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
expiration_date: Optional[date] = None
status_id: Optional[int] = None
is_favorite: Optional[bool] = None
Usage in Routes:
@router.post("/", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(task: TaskCreate, current_user: User = Depends(get_current_user)) -> Task:
task_created = TaskService.create_task(
title=task.title,
description=task.description,
expiration_date=task.expiration_date,
status_id=task.status_id,
user_id=current_user.id
)
return task_created
@router.put("/{task_id}", response_model=Task)
def update_task(task_id: int, task_update: TaskUpdate, current_user: User = Depends(get_current_user)) -> Task:
updates = task_update.dict(exclude_unset=True)
is_admin = current_user.role.name == "Administrador"
task = TaskService.update_task(
task_id=task_id,
user_id=current_user.id,
is_admin=is_admin,
**updates
)
if task:
return task
raise HTTPException(status_code=404, detail="Tarea no encontrada")
3. Enhanced Validation and Error Handling
Issue: Insufficient Validation
- Current implementation assumes that the
status_id and other fields are valid. It’s beneficial to add validation to ensure that the provided status_id exists or that the expiration_date is in the future.
Recommendation: Add Validation in Pydantic Models or Services
from pydantic import validator
class TaskCreate(BaseModel):
# ... existing fields
@validator('expiration_date')
def check_expiration_date(cls, v):
if v and v < date.today():
raise ValueError("Expiration date must be in the future")
return v
Improvement: Detailed Error Messages
- Provide more specific error messages to help clients understand what went wrong.
Example:
if not task:
raise HTTPException(status_code=404, detail="Tarea no encontrada")
elif not permission:
raise HTTPException(status_code=403, detail="No tienes permiso para acceder a esta tarea")
4. Security Enhancements
Issue: Role-Based Access Control (RBAC)
- Currently, only the “Administrador” role has elevated privileges. Ensure that role checks are consistent and secure across all routes.
Recommendation: Implement RBAC Middleware or Decorators
Instead of manually checking current_user.role.name, consider creating utility functions or decorators to handle role-based access.
def admin_required(current_user: User = Depends(get_current_user)):
if current_user.role.name != "Administrador":
raise HTTPException(status_code=403, detail="Administrador requerido")
return current_user
Usage in Routes:
@router.delete("/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_task(task_id: int, current_user: User = Depends(admin_required)):
# Only admin can delete tasks
success = TaskService.delete_task(task_id=task_id, user_id=current_user.id, is_admin=True)
if success:
return
raise HTTPException(status_code=404, detail="Tarea no encontrada")
5. Pagination and Filtering
Issue: Scalability in list_tasks
- Listing all tasks without pagination can lead to performance issues as the number of tasks grows.
Recommendation: Implement Pagination Parameters
@router.get("/", response_model=List[Task])
def list_tasks(
status: Optional[str] = None,
expiration_date: Optional[date] = None,
limit: int = 10,
offset: int = 0,
current_user: User = Depends(get_current_user)
) -> List[Task]:
is_admin = current_user.role.name == "Administrador"
tasks = TaskService.list_tasks(
user_id=current_user.id,
status=status,
expiration_date=expiration_date,
is_admin=is_admin,
limit=limit,
offset=offset
)
return tasks
Update TaskService.list_tasks to Handle Pagination
Ensure your TaskService.list_tasks method accepts and utilizes limit and offset parameters.
6. Optimizing Database Queries
Issue: Potential N+1 Queries
- In the
get_task_changes route, fetching changes might lead to N+1 queries if not optimized, depending on the ORM.
Recommendation: Use Efficient Querying Techniques
Leverage ORM features such as select_related or prefetch_related (if using Django ORM) or appropriate joins in SQLAlchemy to optimize queries.
7. Response Schemas and Serialization
Issue: Inconsistent Data Types
- The
ChangeModelOut uses timestamp: date, which might not capture time. Consider using datetime for more precise timestamps.
Recommendation: Update to datetime
from datetime import datetime
class ChangeModelOut(BaseModel):
# ... existing fields
timestamp: datetime # Changed from date to datetime
Enhancement: Include Related Data
For better client experience, consider including related data in your response models, such as user information who made the change.
class ChangeModelOut(BaseModel):
id: int
task_id: int
timestamp: datetime
field_changed: str
old_value: Optional[str] = None
new_value: Optional[str] = None
changed_by: Optional[str] = None # Username or user ID
class Config:
orm_mode = True
8. Documentation and Documentation Enhancements
Issue: Limited API Documentation
- While your route docstrings are helpful, integrating with tools like OpenAPI to auto-generate comprehensive API docs can enhance usability.
Recommendation: Utilize Swagger/OpenAPI Features
FastAPI automatically generates interactive API documentation. Ensure all routes and models are well-documented to take full advantage.
Example: Add Descriptions and Examples in Pydantic Models
class TaskCreate(BaseModel):
title: str = Field(..., example="Comprar leche")
description: Optional[str] = Field(None, example="Comprar leche en el supermercado")
expiration_date: Optional[date] = Field(None, example="2023-12-31")
status_id: Optional[int] = Field(1, example=1)
9. Additional Features and Enhancements
Feature: Search Functionality
- Implement search capabilities to allow users to search tasks by title or description.
Feature: Sorting
- Allow sorting of tasks based on different fields like
expiration_date, created_at, etc.
Feature: Bulk Operations
- Enable bulk creation, updating, or deletion of tasks to improve efficiency.
Feature: Rate Limiting
- Implement rate limiting to prevent abuse and ensure fair usage of the API.
10. Code Consistency and Style
Issue: Consistent Naming Conventions
- Ensure consistency in naming, such as using either English or Spanish for variable names and comments.
Recommendation: Stick to One Language
While your code contains Spanish comments and variable names, consider maintaining consistency throughout the codebase to avoid confusion.
Example:
class ChangeModelOut(BaseModel):
field_changed: str # "campo_cambiado"
old_value: Optional[str] = None # "valor_antiguo"
new_value: Optional[str] = None # "valor_nuevo"
Choose either English or Spanish for all identifiers and comments.
11. Testing
Issue: Lack of Unit and Integration Tests
- Ensure that you have comprehensive tests covering all routes, including edge cases and error scenarios.
Recommendation: Implement Tests Using pytest and TestClient
Create test cases for each route to validate functionality, permissions, and error handling.
Example: Basic Test for create_task
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_task():
response = client.post(
"/tasks/",
json={"title": "Test Task", "description": "Test Description"}
)
assert response.status_code == 201
assert response.json()["title"] == "Test Task"
12. Performance Optimization
Issue: Potential Bottlenecks in Data Retrieval
- As your application scales, certain routes might become performance bottlenecks, especially those retrieving large datasets.
Recommendation: Implement Caching
Use caching strategies (like Redis) to cache frequently accessed data, reducing database load and improving response times.
Final Revised Code Example
Incorporating some of the above recommendations, here's how your create_task route might look:
from fastapi import APIRouter, HTTPException, Depends, status
from typing import List, Optional
from datetime import date, datetime
from pydantic import BaseModel, Field, validator
from models.task import Task
from models.user import User
from models.change import Change
from services.task_service import TaskService
from utils.dependencies import get_current_user, get_current_admin
router = APIRouter(
prefix="/tasks",
tags=["tasks"],
)
class TaskCreate(BaseModel):
title: str = Field(..., example="Comprar leche")
description: Optional[str] = Field(None, example="Comprar leche en el supermercado")
expiration_date: Optional[date] = Field(None, example="2023-12-31")
status_id: Optional[int] = Field(1, example=1)
@validator('expiration_date')
def check_expiration_date(cls, v):
if v and v < date.today():
raise ValueError("Expiration date must be in the future")
return v
class TaskUpdate(BaseModel):
title: Optional[str] = Field(None, example="Comprar leche")
description: Optional[str] = Field(None, example="Comprar leche en el supermercado")
expiration_date: Optional[date] = Field(None, example="2023-12-31")
status_id: Optional[int] = Field(None, example=2)
is_favorite: Optional[bool] = Field(None, example=True)
class ChangeModelOut(BaseModel):
id: int
task_id: int
timestamp: datetime
field_changed: str
old_value: Optional[str] = None
new_value: Optional[str] = None
changed_by: Optional[str] = None # Assuming you have this field
class Config:
orm_mode = True
@router.post("/", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(task: TaskCreate, current_user: User = Depends(get_current_user)) -> Task:
try:
task_created = TaskService.create_task(
title=task.title,
description=task.description,
expiration_date=task.expiration_date,
status_id=task.status_id,
user_id=current_user.id
)
return task_created
except ValidationError as ve:
raise HTTPException(status_code=400, detail=str(ve))
except Exception as e:
raise HTTPException(status_code=500, detail="Internal Server Error")
Note: The above example assumes that you've updated the TaskService.create_task method to handle the new parameters and validations accordingly.
Conclusion
Your FastAPI module provides a solid foundation for task management with essential CRUD operations and change tracking. By implementing the suggested improvements, you can enhance the robustness, scalability, and maintainability of your application. Always ensure to follow best practices in security, validation, and code organization to build a reliable and efficient API.
If you have specific questions or need further assistance on certain parts of your code, feel free to ask!