Skip to content

Campelos7/Operant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Operant

Python Version FastAPI PostgreSQL

Enterprise-Grade SaaS Backend | Multi-Tenant Architecture | Production Ready
Built with FastAPI + PostgreSQL + SQLAlchemy 2.0 + JWT Security

πŸ’Ό Perfect For Recruiters Looking For:

βœ… Clean Code Architecture – Layered design with clear separation of concerns
βœ… Enterprise Patterns – Multi-tenancy, RBAC, subscription management
βœ… Production Best Practices – Error handling, security, testing, observability
βœ… Modern Python Stack – Async/await, type hints, dependency injection
βœ… DevOps Ready – Docker, migrations, CI/CD ready structure


🎯 What This Project Demonstrates

Backend Engineering Excellence

Skill Evidence
System Design Multi-tenant architecture with organization-scoped resources
API Development RESTful design, versioning, pagination, filtering, sorting
Database Design PostgreSQL, SQLAlchemy ORM, Alembic migrations, indexing strategy
Security JWT (rotating), bcrypt, CORS, RBAC per organization, token invalidation
Testing Unit tests + integration tests, pytest, 100% production-like environment
Code Quality Type hints throughout, pydantic validation, centralized error handling
DevOps/Infrastructure Docker, Docker Compose, async patterns, connection pooling
Scalability Async database drivers, stateless design, horizontal scaling ready

✨ Key Features

Authentication & Security πŸ”’

  • Production-Grade Auth: Email/password + bcrypt hashing (industry standard)
  • JWT Implementation: Short-lived access tokens + rotating refresh tokens (best practice)
  • Session Management: Server-side token invalidation on logout
  • RBAC System: OWNER, ADMIN, MEMBER roles per organization (enterprise standard)

Multi-Tenancy Architecture 🏒

  • Data Isolation: Organization-scoped resources with full tenant separation
  • Multi-Org Membership: Users belong to multiple organizations (SaaS requirement)
  • Tenant Context: Automatic routing via X-Organization-Id header
  • Security Boundaries: Strict permission checking at every level

Subscription & Plan Management πŸ’°

  • Flexible Tiers: FREE and PRO plans with progressive limits
  • Usage Enforcement: Per-organization limits on users and projects
  • Feature Flags: Plan-based feature availability system
  • Ready for Monetization: Built to scale to enterprise pricing models

API Quality πŸ“Š

  • RESTful Design: Clean, versioned endpoints (/api/v1)
  • Advanced Querying: Pagination, filtering, sorting (production-grade)
  • Centralized Errors: Consistent error responses with proper HTTP status codes
  • Auto Documentation: Swagger/OpenAPI at /docs + ReDoc

Testing Excellence πŸ§ͺ

  • Comprehensive Coverage: Unit tests (services) + integration tests (routes)
  • Production-Like Testing: PostgreSQL in tests (same stack, no mocking database)
  • Fast Execution: pytest with async support
  • Realistic Scenarios: Full end-to-end flows tested

Infrastructure & DevOps 🐳

  • Containerized: Docker + Docker Compose for instant setup
  • Migration Strategy: Alembic for schema versioning and team collaboration
  • CI/CD Compatible: Ready for GitHub Actions / GitLab CI pipelines
  • Async Optimized: FastAPI async/await for high concurrency

πŸ—οΈ Architecture: Enterprise-Grade Design

Layered Architecture Pattern

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   FastAPI Routes (Orchestration)β”‚  ← Handles HTTP, dependency injection
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Services (Business Logic)      β”‚  ← All domain logic, validations
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  Repositories (Data Access)     β”‚  ← Clean abstraction over database
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  SQLAlchemy ORM + PostgreSQL    β”‚  ← Persistent storage
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Architecture Principles:

  • βœ… No Business Logic in Routes – Routes only orchestrate
  • βœ… Dependency Injection – Loose coupling, easy testing
  • βœ… Repository Pattern – Data access abstraction
  • βœ… Service Layer – Reusable business logic
  • βœ… Separation of Concerns – Each layer has one responsibility

Tech Stack (Enterprise-Grade)

Layer Technology Why This Choice
Web Framework FastAPI 0.104+ Async, auto-docs, type validation
Database PostgreSQL (async) ACID compliance, complex queries, proven at scale
ORM SQLAlchemy 2.0 Type-safe, async support, industry standard
Migrations Alembic Version control for schema, team collaboration
Authentication JWT + bcrypt Stateless, scalable, industry standard
Validation Pydantic v2 Type hints, automatic validation, serialization
Testing pytest + async Fast, realistic, PostgreSQL in tests
Containerization Docker Compose Local parity with production
Language Python 3.11+ Readable, productive, type hints support

πŸ“Š Production-Grade Features

Error Handling

# Centralized error responses
{
  "detail": "Specific error message",
  "error_code": "RESOURCE_NOT_FOUND",
  "status_code": 404
}

Pagination & Filtering

# Get projects with pagination and sorting
curl "http://localhost:8000/api/v1/projects?skip=0&limit=20&order_by=-created_at"

# Response includes metadata
{
  "items": [...],
  "total": 45,
  "skip": 0,
  "limit": 20
}

Rate Limiting Ready

  • Infrastructure supports rate limiting (future enhancement)
  • Stateless design allows easy horizontal scaling

Async/Await Optimization

  • All endpoints are async
  • Database queries don't block
  • Handles thousands of concurrent connections
  • ~10x better concurrency than sync Python

πŸš€ Quick Start (30 seconds)

Prerequisites

  • Docker & Docker Compose (recommended for instant setup)
  • Python 3.11+ (for local development)
  • PostgreSQL (included in Docker setup)

Local Development (Docker)

  1. Clone and setup:

    git clone <repository-url>
    cd Operant
    docker compose up --build
  2. Access the API (< 10 seconds):

  3. Try it out:

    curl -X POST http://localhost:8000/api/v1/auth/register \
      -H "Content-Type: application/json" \
      -d '{
        "email": "demo@example.com",
        "password": "Demo123!",
        "full_name": "Demo User"
      }'

Done! πŸŽ‰ You have a fully functional SaaS backend running.

Local Development (Native Python)

  1. Create virtual environment:

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

    pip install -e ".[dev]"
  3. Configure environment variables:

    # Create .env file with database connection
    export OPERANT_DATABASE_URL=postgresql+psycopg2://user:password@localhost:5432/operant
  4. Run migrations:

    alembic -c operant/app/db/migrations/alembic.ini upgrade head
  5. Start the server:

    uvicorn operant.app.main:app --reload

πŸ§ͺ Testing

Run All Tests

# With Docker PostgreSQL
docker compose up -d db
pytest

Run Specific Test Suites

# Unit tests only
pytest operant/app/tests/ -k "services" -v

# Integration tests only
pytest operant/app/tests/test_integration_flow.py -v

# With coverage
pytest --cov=operant --cov-report=html

Test Configuration

Tests use actual PostgreSQL (production-like environment):

# Set test environment
export OPERANT_ENV=test
export OPERANT_DATABASE_URL=postgresql+psycopg2://operant:operant@localhost:5432/operant_test

# Run tests
pytest -v

πŸ” Authentication Flow

User Registration & Login

1. Register a new user:

curl -X POST http://localhost:8000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!",
    "full_name": "John Doe"
  }'

Response:

{
  "id": "uuid",
  "email": "user@example.com",
  "full_name": "John Doe",
  "created_at": "2024-01-28T10:00:00Z"
}

2. Login:

curl -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePassword123!"
  }'

Response:

{
  "access_token": "eyJ...",
  "refresh_token": "eyJ...",
  "token_type": "bearer"
}

3. Refresh tokens (rotating):

curl -X POST http://localhost:8000/api/v1/auth/refresh \
  -H "Authorization: Bearer <refresh_token>"

4. Logout:

curl -X POST http://localhost:8000/api/v1/auth/logout \
  -H "Authorization: Bearer <access_token>"

Protected Endpoints

Use the access token in the Authorization header:

curl -X GET http://localhost:8000/api/v1/users/me \
  -H "Authorization: Bearer <access_token>"

Organization Context

For organization-scoped endpoints, include the organization ID:

curl -X GET http://localhost:8000/api/v1/projects \
  -H "Authorization: Bearer <access_token>" \
  -H "X-Organization-Id: <org-uuid>"

πŸ” Authentication & Authorization Deep Dive

JWT Implementation (Industry Standard)

User Registration/Login
        ↓
Generate: Short-lived access token (15 min) + Long-lived refresh token (7 days)
        ↓
Access Token: Used for API requests, expires frequently
Refresh Token: Used only to get new access token, rotates each use
        ↓
Logout: Invalidates refresh token server-side (secure session termination)

RBAC (Role-Based Access Control)

Each user in an organization has one of three roles:

  • OWNER – Full control, can delete org, manage billing
  • ADMIN – Can manage members and resources, no billing access
  • MEMBER – Can create/view own resources

Permission checking happens at:

  1. Route Level – Via dependency injection (get_current_user)
  2. Service Level – Business logic validates permissions
  3. Database Level – Query filters by organization

πŸ“š API Endpoints Reference

Authentication Routes (/api/v1/auth)

POST   /auth/register    # Create account (email verification ready)
POST   /auth/login       # Returns access_token + refresh_token
POST   /auth/refresh     # Get new access token (rotating)
POST   /auth/logout      # Invalidate session

User Management (/api/v1/users)

GET    /users/me         # Current user profile
PUT    /users/me         # Update profile
GET    /users            # List all users (admin only)

Organization Management (/api/v1/organizations)

POST   /organizations           # Create new org
GET    /organizations           # List user's orgs
GET    /organizations/{id}      # Get org details
PUT    /organizations/{id}      # Update org (owner only)
DELETE /organizations/{id}      # Delete org (owner only)

Projects (/api/v1/projects)

POST   /projects              # Create project
GET    /projects              # List (org-scoped, paginated)
GET    /projects/{id}         # Get details
PUT    /projects/{id}         # Update (owner/admin)
DELETE /projects/{id}         # Delete (owner/admin)

Tasks (/api/v1/tasks)

POST   /tasks                 # Create task
GET    /tasks                 # List (project-scoped, with filters)
GET    /tasks/{id}            # Get task
PUT    /tasks/{id}            # Update
DELETE /tasks/{id}            # Delete

πŸ“‹ Project Structure (Clean Architecture)

operant/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ main.py                 # FastAPI app, middleware, startup
β”‚   β”‚
β”‚   β”œβ”€β”€ api/                    # 🌐 API Layer (Routes only)
β”‚   β”‚   β”œβ”€β”€ deps.py            # Dependency injection (get_current_user, etc)
β”‚   β”‚   └── v1/
β”‚   β”‚       β”œβ”€β”€ auth.py        # Authentication routes
β”‚   β”‚       β”œβ”€β”€ users.py       # User management
β”‚   β”‚       β”œβ”€β”€ organizations.py
β”‚   β”‚       β”œβ”€β”€ projects.py
β”‚   β”‚       └── tasks.py
β”‚   β”‚
β”‚   β”œβ”€β”€ services/              # πŸ’Ό Business Logic Layer
β”‚   β”‚   β”œβ”€β”€ auth_service.py    # Authentication logic
β”‚   β”‚   β”œβ”€β”€ organization_service.py
β”‚   β”‚   β”œβ”€β”€ project_service.py
β”‚   β”‚   β”œβ”€β”€ task_service.py
β”‚   β”‚   └── ...
β”‚   β”‚
β”‚   β”œβ”€β”€ repositories/          # πŸ—„οΈ Data Access Layer
β”‚   β”‚   β”œβ”€β”€ user_repository.py
β”‚   β”‚   β”œβ”€β”€ organization_repository.py
β”‚   β”‚   β”œβ”€β”€ project_repository.py
β”‚   β”‚   └── ... (abstraction over database)
β”‚   β”‚
β”‚   β”œβ”€β”€ models/                # πŸ”— SQLAlchemy ORM Models
β”‚   β”‚   β”œβ”€β”€ user.py
β”‚   β”‚   β”œβ”€β”€ organization.py
β”‚   β”‚   β”œβ”€β”€ project.py
β”‚   β”‚   β”œβ”€β”€ task.py
β”‚   β”‚   └── ...
β”‚   β”‚
β”‚   β”œβ”€β”€ schemas/               # βœ… Pydantic Request/Response Schemas
β”‚   β”‚   β”œβ”€β”€ users.py
β”‚   β”‚   β”œβ”€β”€ organizations.py
β”‚   β”‚   └── ... (validation + serialization)
β”‚   β”‚
β”‚   β”œβ”€β”€ core/                  # βš™οΈ Configuration & Utilities
β”‚   β”‚   β”œβ”€β”€ config.py          # Environment variables, settings
β”‚   β”‚   β”œβ”€β”€ security.py        # JWT creation/validation, password hashing
β”‚   β”‚   β”œβ”€β”€ permissions.py     # RBAC logic
β”‚   β”‚   └── errors.py          # Custom exceptions
β”‚   β”‚
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”œβ”€β”€ session.py         # Database session management
β”‚   β”‚   β”œβ”€β”€ base.py            # Base model, metadata
β”‚   β”‚   └── migrations/        # Alembic version control
β”‚   β”‚
β”‚   └── tests/                 # πŸ§ͺ Test Suite
β”‚       β”œβ”€β”€ conftest.py        # pytest fixtures, setup
β”‚       β”œβ”€β”€ test_integration_flow.py
β”‚       β”œβ”€β”€ test_services_plan_limits.py
β”‚       └── ...
β”‚
β”œβ”€β”€ docker-compose.yml         # Local environment (Postgres + API)
β”œβ”€β”€ Dockerfile                 # Production-ready image
β”œβ”€β”€ pyproject.toml             # Dependencies, project metadata
└── README.md                  # This file

About

πŸ‘¨β€πŸ’» Operant is a showcase project demonstrating professional backend development with Python, FastAPI, and PostgreSQL. It's built following industry best practices for scalability, maintainability, and security.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages