Skip to content

deep-coder-art/fastapi-mvc

Repository files navigation

FastAPI MVC Application

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.

Features

  • 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

Tech Stack

  • 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

Project Structure

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

Installation

Prerequisites

  • Python 3.8+
  • MySQL 5.7+ or 8.0+
  • pip (Python package manager)

Setup

  1. Clone the repository (if applicable) or navigate to the project directory:

    cd backend_test
  2. Create a virtual environment (recommended):

    python -m venv venv
    
    # On Windows
    venv\Scripts\activate
    
    # On macOS/Linux
    source venv/bin/activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. 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
  5. Create Database:

    CREATE DATABASE fastapi_db;

    (Replace fastapi_db with your chosen database name)

  6. Run Database Migrations:

    # Create initial migration (first time setup)
    python manage_migrations.py init
    
    # Apply migrations to create tables
    python manage_migrations.py upgrade
  7. Run the application:

    python main.py

    Or using uvicorn directly:

    uvicorn main:app --reload --host 0.0.0.0 --port 8000

API Documentation

The application automatically generates interactive API documentation:

API Endpoints

Authentication

POST /api/v1/auth/signup

Register a new user account.

Request Body:

{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 1800
}

POST /api/v1/auth/login

Authenticate user and get access token.

Request Body:

{
  "email": "user@example.com",
  "password": "SecurePassword123!"
}

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 1800
}

Posts

All post endpoints require authentication. Include the token in the Authorization header:

Authorization: Bearer <your_token_here>

POST /api/v1/posts/

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 /api/v1/posts/

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 /api/v1/posts/{post_id}

Delete a specific post.

Response: 204 No Content

Usage Examples

Python Requests

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)

cURL Examples

# 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"

Architecture Details

MVC Pattern Implementation

  1. Models (models/):

    • sqlalchemy_models.py: Database entities (User, Post)
    • pydantic_models.py: Request/response validation schemas
  2. Views/Controllers (controllers/):

    • auth_controller.py: Authentication endpoints
    • posts_controller.py: Post management endpoints
  3. Services (services/):

    • auth_service.py: Authentication business logic
    • user_service.py: User management logic
    • post_service.py: Post management logic with caching

Key Features

  • 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

Security & Configuration

Environment Variables

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 string
  • SECRET_KEY: JWT token signing key (auto-generated by setup script)
  • ACCESS_TOKEN_EXPIRE_MINUTES: Token expiration time
  • MAX_PAYLOAD_SIZE: Maximum request payload size (1MB)
  • CACHE_TTL_SECONDS: Cache time-to-live (300 seconds)

Security Features

  • Environment Variables: Sensitive configuration stored in .env file
  • 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

Files Excluded from Version Control

The .gitignore file is configured to exclude:

  • .env files (environment variables)
  • Database files
  • Python cache files
  • IDE configuration files
  • Log files
  • Temporary files

Development

Running in Development Mode

uvicorn main:app --reload --host 0.0.0.0 --port 8000

Database Migrations

The 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 -1

For detailed migration guide, see MIGRATIONS.md.

Testing

The application includes comprehensive error handling and validation. Test the API using the interactive documentation at /docs or use the provided examples.

Production Deployment

For production deployment:

  1. Set environment variables for sensitive configuration
  2. Use a production ASGI server like Gunicorn with Uvicorn workers
  3. Configure proper CORS settings
  4. Set up SSL/TLS certificates
  5. Use a reverse proxy like Nginx
  6. Configure logging and monitoring

License

This project is provided as-is for educational and development purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors