A comprehensive web application built with FastAPI following the MVC (Model-View-Controller) design pattern. This application provides user authentication, post management, and implements advanced features like JWT authentication, caching, and comprehensive validation.
- MVC Architecture: Clean separation of concerns with Models, Views (Controllers), and Services
- JWT Authentication: Secure token-based authentication system
- SQLAlchemy ORM: Database operations with MySQL support
- Pydantic Validation: Comprehensive input validation and type checking
- Caching: 5-minute TTL cache for improved performance
- Dependency Injection: Clean and testable code structure
- API Documentation: Auto-generated OpenAPI/Swagger documentation
- FastAPI: Modern, fast web framework for building APIs
- SQLAlchemy: Python SQL toolkit and Object-Relational Mapping
- MySQL: Relational database management system
- JWT: JSON Web Token for secure authentication
- Pydantic: Data validation using Python type annotations
- Uvicorn: Lightning-fast ASGI server
backend_test/
├── main.py # FastAPI application entry point
├── config.py # Configuration settings
├── database.py # Database configuration
├── dependencies.py # Dependency injection functions
├── requirements.txt # Python dependencies
├── README.md # Project documentation
├── MIGRATIONS.md # Database migrations guide
├── manage_migrations.py # Migration management script
├── create_env.py # Environment setup script
├── run.py # Application startup script
├── env.example # Environment variables template
├── .gitignore # Git ignore rules
├── alembic/ # Database migrations
│ ├── versions/ # Migration files
│ ├── env.py # Migration environment
│ └── script.py.mako # Migration template
├── alembic.ini # Alembic configuration
├── models/
│ ├── __init__.py
│ ├── sqlalchemy_models.py # SQLAlchemy database models
│ └── pydantic_models.py # Pydantic validation models
├── services/
│ ├── __init__.py
│ ├── auth_service.py # Authentication business logic
│ ├── user_service.py # User management business logic
│ └── post_service.py # Post management business logic
└── controllers/
├── __init__.py
├── auth_controller.py # Authentication endpoints
└── posts_controller.py # Post management endpoints
- Python 3.8+
- MySQL 5.7+ or 8.0+
- pip (Python package manager)
-
Clone the repository (if applicable) or navigate to the project directory:
cd backend_test -
Create a virtual environment (recommended):
python -m venv venv # On Windows venv\Scripts\activate # On macOS/Linux source venv/bin/activate
-
Install dependencies:
pip install -r requirements.txt
-
Configure Environment Variables:
Option A: Use the automated setup script (Recommended):
python create_env.py
This script will:
- Generate a secure random SECRET_KEY
- Prompt for database credentials
- Create a .env file with proper configuration
Option B: Manual setup:
# Copy the example file cp env.example .env # Edit .env with your actual values nano .env # or use your preferred editor
-
Create Database:
CREATE DATABASE fastapi_db;
(Replace
fastapi_dbwith your chosen database name) -
Run Database Migrations:
# Create initial migration (first time setup) python manage_migrations.py init # Apply migrations to create tables python manage_migrations.py upgrade
-
Run the application:
python main.py
Or using uvicorn directly:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
The application automatically generates interactive API documentation:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Register a new user account.
Request Body:
{
"email": "user@example.com",
"password": "SecurePassword123!"
}Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 1800
}Authenticate user and get access token.
Request Body:
{
"email": "user@example.com",
"password": "SecurePassword123!"
}Response:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "bearer",
"expires_in": 1800
}All post endpoints require authentication. Include the token in the Authorization header:
Authorization: Bearer <your_token_here>
Create a new post.
Request Body:
{
"text": "This is my first post!"
}Response:
{
"id": 1,
"text": "This is my first post!",
"owner_id": 1,
"created_at": "2023-01-01T12:00:00Z",
"updated_at": "2023-01-01T12:00:00Z"
}Get all posts for the authenticated user (cached for 5 minutes).
Response:
{
"posts": [
{
"id": 1,
"text": "This is my first post!",
"owner_id": 1,
"created_at": "2023-01-01T12:00:00Z",
"updated_at": "2023-01-01T12:00:00Z"
}
],
"total_count": 1
}Delete a specific post.
Response: 204 No Content
import requests
BASE_URL = "http://localhost:8000/api/v1"
# 1. Sign up
signup_data = {
"email": "test@example.com",
"password": "SecurePass123!"
}
response = requests.post(f"{BASE_URL}/auth/signup", json=signup_data)
token = response.json()["access_token"]
# 2. Create a post
headers = {"Authorization": f"Bearer {token}"}
post_data = {"text": "Hello, World!"}
response = requests.post(f"{BASE_URL}/posts/", json=post_data, headers=headers)
post_id = response.json()["id"]
# 3. Get posts
response = requests.get(f"{BASE_URL}/posts/", headers=headers)
posts = response.json()
# 4. Delete a post
response = requests.delete(f"{BASE_URL}/posts/{post_id}", headers=headers)# Sign up
curl -X POST "http://localhost:8000/api/v1/auth/signup" \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "password": "SecurePass123!"}'
# Login
curl -X POST "http://localhost:8000/api/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "password": "SecurePass123!"}'
# Create post (replace TOKEN with actual token)
curl -X POST "http://localhost:8000/api/v1/posts/" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer TOKEN" \
-d '{"text": "Hello, World!"}'
# Get posts
curl -X GET "http://localhost:8000/api/v1/posts/" \
-H "Authorization: Bearer TOKEN"
# Delete post (replace 1 with actual post ID)
curl -X DELETE "http://localhost:8000/api/v1/posts/1" \
-H "Authorization: Bearer TOKEN"-
Models (
models/):sqlalchemy_models.py: Database entities (User, Post)pydantic_models.py: Request/response validation schemas
-
Views/Controllers (
controllers/):auth_controller.py: Authentication endpointsposts_controller.py: Post management endpoints
-
Services (
services/):auth_service.py: Authentication business logicuser_service.py: User management logicpost_service.py: Post management logic with caching
- Dependency Injection: Clean separation using FastAPI's dependency system
- Database Migrations: Alembic-based schema version control
- Caching: TTL-based caching for improved performance
- Validation: Comprehensive input validation with detailed error messages
- Security: JWT tokens, password hashing, and proper authentication
- Error Handling: Consistent error responses across the application
The application uses environment variables for secure configuration. All sensitive data should be stored in a .env file (which is automatically excluded from version control).
Key configuration options:
DATABASE_URL: MySQL database connection stringSECRET_KEY: JWT token signing key (auto-generated by setup script)ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration timeMAX_PAYLOAD_SIZE: Maximum request payload size (1MB)CACHE_TTL_SECONDS: Cache time-to-live (300 seconds)
- Environment Variables: Sensitive configuration stored in
.envfile - Auto-generated Secret Keys: Cryptographically secure JWT signing keys
- Password Hashing: Bcrypt with secure defaults
- Input Validation: Comprehensive Pydantic validation
- SQL Injection Protection: SQLAlchemy ORM prevents SQL injection
- CORS Configuration: Configurable for production security
- Token Expiration: JWT tokens expire automatically
The .gitignore file is configured to exclude:
.envfiles (environment variables)- Database files
- Python cache files
- IDE configuration files
- Log files
- Temporary files
uvicorn main:app --reload --host 0.0.0.0 --port 8000The project uses Alembic for database schema management:
# Create a new migration
python manage_migrations.py create "Add new feature"
# Apply migrations
python manage_migrations.py upgrade
# Show migration history
python manage_migrations.py history
# Rollback to previous version
python manage_migrations.py downgrade -1For detailed migration guide, see MIGRATIONS.md.
The application includes comprehensive error handling and validation. Test the API using the interactive documentation at /docs or use the provided examples.
For production deployment:
- Set environment variables for sensitive configuration
- Use a production ASGI server like Gunicorn with Uvicorn workers
- Configure proper CORS settings
- Set up SSL/TLS certificates
- Use a reverse proxy like Nginx
- Configure logging and monitoring
This project is provided as-is for educational and development purposes.