Development Guide
Project Setup
Prerequisites
- Python 3.8+
- PostgreSQL or MySQL
- Redis (for caching and message queue)
- pip
- virtualenv (recommended)
Environment Setup
-
Create and activate a virtual environment:
-
Install dependencies:
-
Set up environment variables:
Edit the.envfile with your configuration.
Database Setup
PostgreSQL:
MySQL:
-
Configure database in
.env: -
Run migrations:
Redis Setup
macOS (Homebrew):
Docker:
Linux:
Verify Redis is running:
Development Workflow
Running the Development Server
The server will be available at http://localhost:8000Authentication
Register a New User
The registration endpoint automatically logs in the user and returns an authorization token:
curl -X POST http://localhost:8000/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "Test@12345",
"full_name": "John Doe"
}'
Response includes: - id: User ID - email: User email - full_name: User full name - is_active: Active status - is_superuser: Superuser status - created_at: Creation timestamp - updated_at: Update timestamp
Note: After registration, use the /api/v1/auth/login endpoint to get an authorization token.
Login
curl -X POST http://localhost:8000/api/v1/auth/login \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "username=user@example.com&password=Test@12345"
Response includes: - access_token: JWT token for API authentication - token_type: "bearer" - user: Complete user information
Using Authentication Tokens
⚠️ IMPORTANT: All API endpoints require authentication EXCEPT login and register.
All protected endpoints require the Authorization header:
Protected Endpoints (Require Token): - All /api/v1/users/* endpoints - All /api/v1/files/* endpoints - All /api/v1/broadcasting/* endpoints
Public Endpoints (No Token Required): - POST /api/v1/auth/register - POST /api/v1/auth/login
Without a valid token, you'll receive:
Password Requirements
- Minimum 8 characters
- Maximum 512 characters (bcrypt limitation handled automatically)
- At least one uppercase letter
- At least one lowercase letter
- At least one digit
API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Database Migrations
Creating a new migration
Applying migrations
Rolling back migrations
Redis Caching
The boilerplate includes a Laravel-like caching interface:
from app.core.cache import cache
# Store value
cache().put("key", "value", ttl=3600)
# Get value
value = cache().get("key", default=None)
# Cache-aside pattern (recommended)
user = cache().remember(
f"user:{user_id}",
ttl=300,
callback=lambda: User.get(db, id=user_id)
)
# Invalidate cache
cache().forget("key")
See Redis Usage Guide for more examples.
Background Tasks (Celery)
Start Celery Worker:
# Development (with auto-reload)
celery -A app.core.celery_app worker --loglevel=info --reload
# Production
celery -A app.core.celery_app worker --loglevel=info
Monitor with Flower:
Create Background Tasks:
from app.core.celery_app import celery_app
@celery_app.task(name="send_email")
def send_email_task(email: str, subject: str):
# Your task logic here
pass
# Call the task
send_email_task.delay("user@example.com", "Hello")
Testing
Running tests
Running tests with coverage
Code Structure
Adding New Features
- Create a new model in
app/models/ - Create corresponding schemas in
app/schemas/ - Create API controllers in
app/api/v1/controllers/ - Add the new router to
app/api/v1/api.py - Create database migration if needed
Best Practices
- Use type hints for all function parameters and return values
- Write docstrings for all functions and classes
- Follow PEP 8 style guide
- Write tests for new features
- Use Pydantic models for request/response validation
- Keep business logic in models or services
- Use dependency injection for database sessions and other dependencies
Error Handling
- Use FastAPI's built-in HTTPException for error responses
- Create custom exception classes in
app/core/exceptions.pyfor specific error cases - Use Pydantic validation for request data
- Implement proper error logging
- Security: Don't expose sensitive information in error messages
- Use
app/core/error_handler.pyfor secure error handling
Security Best Practices
- Secrets Management
- Never commit
.envfiles - Generate secure random keys for production
- Use environment variables for all secrets
-
Rotate secrets regularly
-
Input Validation
- Always validate user input
- Use Pydantic schemas for request validation
- Sanitize file paths and filenames
-
Validate file types and sizes
-
Authentication & Authorization
- Use strong password requirements
- Implement proper JWT token validation
- Check user permissions before operations
-
Use policies and gates for authorization
-
File Operations
- Validate file paths to prevent path traversal
- Check file types and sizes
- Sanitize filenames
-
Use
app/core/file_security.pyutilities -
Command Execution
- Never execute user input as commands
- Use whitelists for allowed commands
- Avoid
shell=Truein subprocess calls -
Validate command parameters
-
Error Handling
- Don't expose stack traces in production
- Use generic error messages
- Log errors securely
-
Include request IDs for tracking
-
Rate Limiting
- Use Redis for distributed rate limiting
- Set appropriate limits per endpoint
-
Implement stricter limits for auth endpoints
-
Security Headers
- Always include security headers
- Configure CSP properly
-
Use HSTS in production with HTTPS
-
CORS Configuration
- Never use wildcard (
*) in production - Specify exact origins
-
Don't allow credentials with wildcard
-
Dependencies
- Regularly update dependencies
- Scan for known vulnerabilities
- Use
pip-auditorsafetyto check packages
Security Testing
# Check for known vulnerabilities
pip install safety
safety check
# Or use pip-audit
pip install pip-audit
pip-audit
# Run security linter
pip install bandit
bandit -r app/
See Security Guide for comprehensive security information.
Security
- Always use HTTPS in production
- Implement proper authentication and authorization
- Use environment variables for sensitive data
- Implement rate limiting for API endpoints
- Use secure password hashing
- Implement proper CORS configuration
Deployment
Production Setup
- Set up a production database
- Configure environment variables for production
- Set up a reverse proxy (Nginx/Apache)
- Use a process manager (Gunicorn/Uvicorn)
- Set up SSL certificates
- Configure proper logging
Docker Deployment
-
Build the Docker image:
-
Run the container:
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests
- Submit a pull request
Troubleshooting
Common Issues
- Database connection errors
- Check database credentials in
.env - Ensure PostgreSQL/MySQL is running
- Verify database exists
-
For MySQL with MAMP, check
DB_UNIX_SOCKETpath -
Redis connection errors
- Ensure Redis is running:
redis-cli ping - Check Redis configuration in
.env -
Verify Redis port (default: 6379)
-
Celery worker not processing tasks
- Ensure Redis is running
- Check Celery worker is started
- Verify tasks are imported in
celery_app.py -
Check Celery logs for errors
-
Migration errors
- Check for conflicting migrations
-
Verify database schema matches models
-
Authentication issues
- Check JWT configuration
- Verify token expiration
- Check user credentials
Getting Help
- Check the documentation
- Search existing issues
- Create a new issue with detailed information
- Join the community chat