Skip to main content

Production-ready FastAPI framework with RBAC, OAuth, JWT, billing, modular architecture, and base class patterns. Create projects with 'swx new', scaffold with 'swx make:resource --base'.

Project description

๐Ÿš€ SwX-API

Python FastAPI License: MIT Docker Ready CI/CD Made with โค๏ธ

SwX-API is a production-ready, enterprise-grade FastAPI framework designed for building scalable SaaS applications. With comprehensive authentication, authorization, billing, rate limiting, audit logging, and more, it provides everything you need to build and deploy production applications.

Built with โค๏ธ for developers who value flexibility, security, and structure.

๐ŸŽ‰ Framework Status: Production Ready v2.0.0


โœจ Key Features

๐Ÿ” Security & Authentication

  • โœ… Domain Separation - Admin, User, and System domains completely isolated
  • โœ… OAuth2 + JWT - Secure token-based authentication with refresh tokens
  • โœ… Social Login - Google, Facebook, and other OAuth providers
  • โœ… Token Security - Audience validation, expiration, and revocation
  • โœ… Secrets Management - Secure handling of sensitive configuration

๐Ÿ›ก๏ธ Authorization & Access Control

  • โœ… Permission-First RBAC - Fine-grained access control with team scoping
  • โœ… Policy Engine (ABAC) - Attribute-based access control with conditions
  • โœ… Team-Scoped Permissions - Multi-tenant support with team isolation
  • โœ… Fail-Closed Security - Deny by default, explicit allow

๐Ÿ’ฐ Billing & Entitlements

  • โœ… Feature Registry - Centralized feature management
  • โœ… Plan Management - Flexible subscription plans (Free, Pro, Team, Enterprise)
  • โœ… Entitlement Resolution - Automatic feature access checking
  • โœ… Usage Tracking - Quota and metered feature tracking
  • โœ… Stripe Integration - Payment processing support

โšก Performance & Scalability

  • โœ… Async Model - Full async/await support for high performance
  • โœ… Rate Limiting - Plan-based rate limits with burst protection
  • โœ… Redis Caching - In-memory caching for improved performance
  • โœ… Background Jobs - Asynchronous job processing with retries
  • โœ… Connection Pooling - Optimized database connections with health checks

๐Ÿ“Š Operations & Monitoring

  • โœ… Audit Logging - Immutable security and business event logs
  • โœ… Alerting System - Multi-channel alerts (Slack, Email, SMS, Logs)
  • โœ… Health Checks - Comprehensive health monitoring
  • โœ… Runtime Settings - Database-backed configuration management
  • โœ… Background Jobs - Job queue with retry logic and dead-letter queue

๐Ÿ› ๏ธ Developer Experience

  • โœ… Modular Architecture - Clean separation of core and app code
  • โœ… Base Classes Pattern - BaseController, BaseService, BaseRepository for rapid development (v2.0)
  • โœ… SQLModel ORM - Type-safe database models
  • โœ… Alembic Migrations - Database version control
  • โœ… CLI Tools - swx command for scaffolding with --base flag for modern patterns
  • โœ… Comprehensive Documentation - 50+ documentation files
  • โœ… Testing Tools - Unit tests, integration tests, acceptance tests
  • โœ… Docker Ready - Complete Docker Compose setup

๐Ÿ†• What's New in v2.0

BaseController / BaseService / BaseRepository

Reduce boilerplate by 80% with the new base classes pattern:

# v2.0 - Modern pattern (recommended)
from swx_core.controllers.base import BaseController
from swx_core.services.base import BaseService
from swx_core.repositories.base import BaseRepository

class ProductRepository(BaseRepository[Product]):
    def __init__(self):
        super().__init__(model=Product)
    # Automatic: find_by_id, find_all, create, update, delete, search, paginate...

class ProductService(BaseService[Product, ProductRepository]):
    def __init__(self):
        super().__init__(repository=ProductRepository())
    # Automatic: get, create, update, delete with events and validation hooks...

class ProductController(BaseController[Product, Create, Update, Public]):
    def __init__(self):
        super().__init__(model=Product, ...)
        self.register_routes()
    # Automatic: GET, POST, PUT, DELETE endpoints...

New Utilities

  • Unit of Work - Transaction management with automatic commit/rollback
  • Filter Builder - Fluent query filtering and sorting
  • Caching Decorators - @cached, @memoize for Redis operations
  • Rate Limiting - @rate_limit_by_ip, @rate_limit_by_user
  • Testing Utilities - ModelFactory, TestClientWithDB, assertions

CLI Improvements

# Generate resources with base classes (recommended)
swx make:resource Product --base

# Generate legacy patterns
swx make:resource Product

See Migration Guide for upgrading from v1.x.


๐Ÿ“ Project Structure

swx-api-latest-backend/
โ”œโ”€โ”€ swx_core/              # Framework code (reusable)
โ”‚   โ”œโ”€โ”€ auth/              # Authentication (admin, user, system)
โ”‚   โ”œโ”€โ”€ cli/               # CLI commands
โ”‚   โ”œโ”€โ”€ config/            # Configuration
โ”‚   โ”œโ”€โ”€ controllers/       # BaseController (v2.0)
โ”‚   โ”œโ”€โ”€ services/          # BaseService (v2.0)
โ”‚   โ”œโ”€โ”€ repositories/      # BaseRepository (v2.0)
โ”‚   โ”œโ”€โ”€ database/          # Database setup and utilities
โ”‚   โ”œโ”€โ”€ middleware/        # Middleware (CORS, logging, rate limiting)
โ”‚   โ”œโ”€โ”€ models/            # Framework models (User, Role, Permission, etc.)
โ”‚   โ”œโ”€โ”€ rbac/              # RBAC system
โ”‚   โ”œโ”€โ”€ routes/            # Framework routes (admin, user, utils)
โ”‚   โ”œโ”€โ”€ security/          # Security utilities
โ”‚   โ”œโ”€โ”€ services/          # Framework services (billing, jobs, alerts, etc.)
โ”‚   โ””โ”€โ”€ utils/             # Utility functions (pagination, caching, filters...)
โ”œโ”€โ”€ swx_app/               # Application code (your features)
โ”‚   โ”œโ”€โ”€ controllers/       # Application controllers
โ”‚   โ”œโ”€โ”€ models/            # Application models
โ”‚   โ”œโ”€โ”€ repositories/      # Application repositories
โ”‚   โ”œโ”€โ”€ routes/            # Application routes
โ”‚   โ””โ”€โ”€ services/          # Application services
โ”œโ”€โ”€ migrations/            # Alembic migrations
โ”œโ”€โ”€ docs/                  # Comprehensive documentation
โ”‚   โ”œโ”€โ”€ 04-core-concepts/
โ”‚   โ”‚   โ”œโ”€โ”€ BASE_CLASSES.md      # BaseController/BaseService/BaseRepository (NEW)
โ”‚   โ”‚   โ”œโ”€โ”€ UTILITIES.md         # All utility modules (NEW)
โ”‚   โ”‚   โ””โ”€โ”€ USAGE_EXAMPLES.md    # Complete usage examples (NEW)
โ”‚   โ””โ”€โ”€ 07-extending/
โ”‚       โ””โ”€โ”€ MIGRATION_GUIDE.md   # v1.x to v2.0 migration (NEW)
โ”œโ”€โ”€ scripts/               # Utility scripts
โ”œโ”€โ”€ Dockerfile             # Docker configuration
โ”œโ”€โ”€ docker-compose.yml     # Docker Compose (development)
โ””โ”€โ”€ docker-compose.production.yml # Docker Compose (production)

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.10+
  • Docker & Docker Compose (recommended)
  • PostgreSQL 12+
  • Redis 6+

Installation

Option 1: Docker (Recommended)

# Clone repository
git clone <repository-url>
cd swx-api-latest-backend

# Copy environment file
cp .env.example .env

# Edit .env with your configuration
# Then start services
docker compose up --build

# Application will be available at:
# - API: http://localhost:8001/api
# - Docs: http://localhost:8001/docs
# - ReDoc: http://localhost:8001/redoc

Option 2: Local Development

# Clone repository
git clone <repository-url>
cd swx-api-latest-backend

# Create virtual environment
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt
# Or using uv (faster)
uv pip install -r requirements.txt

# Copy environment file
cp .env.example .env

# Run database migrations
alembic upgrade head

# Start development server
uvicorn swx_core.main:app --reload --host 0.0.0.0 --port 8001

Initial Setup

After starting the application:

  1. Seed System Data:

    python scripts/seed_system.py
    
  2. Verify Installation:

    curl http://localhost:8001/api/utils/health-check
    
  3. Access Documentation:


๐Ÿ“š Documentation

SwX-API includes comprehensive documentation covering all aspects of the framework:

Getting Started

Core Concepts (v2.0)

Security

Extending

๐Ÿ“– See Documentation Index for complete documentation structure.


๐Ÿ› ๏ธ Development

CLI Commands

# Generate resources with base classes (v2.0 - recommended)
swx make:resource Product --base

# Generate resources with legacy patterns
swx make:resource Product

# Database migrations
swx db migrate
swx db revision -m "description"

# Code quality
swx format      # Format code
swx lint        # Lint code

# Interactive shell
swx tinker

๐Ÿ“Š Example Usage

Base Classes (v2.0)

# Complete resource in minutes
from swx_core.controllers.base import BaseController
from swx_core.services.base import BaseService
from swx_core.repositories.base import BaseRepository
from swx_core.utils.mixins import FullModelMixin

# Model
class Product(FullModelMixin, table=True):
    name: str
    price: float

# Repository
class ProductRepository(BaseRepository[Product]):
    def __init__(self):
        super().__init__(model=Product)

# Service  
class ProductService(BaseService[Product, ProductRepository]):
    def __init__(self):
        super().__init__(repository=ProductRepository())

# Controller
class ProductController(BaseController[Product, ProductCreate, ProductUpdate, ProductPublic]):
    def __init__(self):
        super().__init__(
            model=Product,
            schema_public=ProductPublic,
            schema_create=ProductCreate,
            schema_update=ProductUpdate,
            prefix="/products",
        )
        self.register_routes()

# Automatic endpoints:
# GET    /products          - List with pagination
# GET    /products/{id}      - Get by ID
# POST   /products          - Create
# PUT    /products/{id}     - Update
# DELETE /products/{id}     - Delete

Authentication

# User domain authentication
from swx_core.security.dependencies import get_current_user

@router.get("/user/profile")
async def get_profile(user: User = Depends(get_current_user)):
    return user

Authorization

# Permission-based access
from swx_core.rbac.dependencies import require_permission

@router.get("/users", dependencies=[Depends(require_permission("user:read"))])
async def list_users():
    ...

Rate Limiting

from swx_core.utils.rate_limit import rate_limit_by_user

@router.get("/api/search")
@rate_limit_by_user(requests=100, window=60)  # 100 req/min
async def search(q: str):
    return await search_service.search(q)

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments

  • FastAPI for the excellent web framework
  • SQLModel for the ORM
  • All contributors and users

๐Ÿ“ž Support

  • Documentation: docs/
  • Issues: GitHub Issues
  • Discussions: GitHub Discussions

Built with โค๏ธ for developers who value flexibility, security, and structure.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

swx_core-2.3.3.tar.gz (484.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swx_core-2.3.3-py3-none-any.whl (368.0 kB view details)

Uploaded Python 3

File details

Details for the file swx_core-2.3.3.tar.gz.

File metadata

  • Download URL: swx_core-2.3.3.tar.gz
  • Upload date:
  • Size: 484.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for swx_core-2.3.3.tar.gz
Algorithm Hash digest
SHA256 10ebdfecbfdcfb3ba89eb0c5c7d4ab014be6c719d19a7209091272db8f7ab9e8
MD5 ae9bc5c8b60dded6363ce6a45275bc75
BLAKE2b-256 3c2d2a59abe4095d8f4639c0f150b731dd7094f47de8d126263c11d363c141ac

See more details on using hashes here.

File details

Details for the file swx_core-2.3.3-py3-none-any.whl.

File metadata

  • Download URL: swx_core-2.3.3-py3-none-any.whl
  • Upload date:
  • Size: 368.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for swx_core-2.3.3-py3-none-any.whl
Algorithm Hash digest
SHA256 4a0a5e5ef2369c2205bb585e350900585cfdb7aa804ddc98f96b04579f059e0f
MD5 03e76fc14b3f01cb125226c7db98f1b9
BLAKE2b-256 e212bd45a841aebf1d9b2aad5150b41d87e92d969a0d13e7380c47cf5b15d59b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page