FastAPI ZCore Framework Logo by Baseryn
By Baseryn · Python 3.11+ · Apache-2.0 · Fully Async

Build with FastAPI.
Add ZCore where it helps.

A pragmatically engineered architectural framework by Baseryn built on top of FastAPI. Absolute freedom. No rigid constraints. Use only what you need, and override everything else.

Context Shielding (Zchema)

Eliminate role-based duplicate schemas. Sensitive fields are pruned dynamically per-user in real-time.

Atomic Transactions

Group multiple operations into all-or-nothing transactions with deferred event dispatch.

Scoped DI

Singleton, transient, and request-scoped dependencies resolved automatically.

Modular Plugins

Organize domains into isolated plugins with topological startup ordering.

30-SECOND PREVIEW

An Empty Repository. Complete CRUD.

No complex setup or rigid base-class nesting. Get production-ready database interactions in two steps.

repo.py
# Step 1: Your standard SQLAlchemy model
from zcore import Base, SoftDeleteMixin

class Task(Base, SoftDeleteMixin):
__tablename__ = "tasks"
id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
title: Mapped[str]
is_completed: Mapped[bool] = mapped_column(default=False)
# Step 2: Inheritance yields async CRUD, keyset pagination, and secure search
from zcore import BaseRepository

class TaskRepo(BaseRepository[Task]):
def __init__(self, db: AsyncSession):
super().__init__(model=Task, db=db)
Async methods, pagination, soft-delete restoration, and policy-guarded search — out of the box.
Or write raw SQLAlchemy query statements instead.
Every single component in ZCore is completely optional. Ignore BaseRepository entirely whenever your logic calls for raw query manipulation.

Pick Only What You Need.

Modular components. Decoupled by design.
Adopt the architectural patterns that simplify your workload, and leave the rest to native FastAPI.

Independent — works completely alone Composable — pairs with DB/Model logic Orchestrated — unified framework infrastructure
Inject[T]🟢 Independent

Type-safe constructor dependency injection mapped directly to FastAPI Depends.

@router.get("/tasks")
async def list_tasks(service: Inject[TaskService]):
    return await service.get_list()
Without: FastAPI Depends(get_task_repo) chains
background_task🟢 Independent

Isolate background scopes, auto-inject IoC dependencies, and manage database sessions safely.

@background_task
async def sync_data(task_id: uuid.UUID, service: TaskService):
    await service.process(task_id)
Without: Manual session lifecycle and context leakage in BackgroundTasks
UnitOfWork🟢 Independent

Safely group database writes. Buffers domain events to trigger only post-commit.

async with UnitOfWork(db, disp) as uow:
    await repo.create(schema)
    uow.register_event("created", task)
Without: Manual transaction blocks
EventDispatcher🟢 Independent

Loosely couple operations with highly concurrent async event publishing.

@on_event("task_completed")
async def handle(payload):
    await notify_user(payload)
Without: Direct, tightly coupled method calls
LocalStorageProvider🟢 Independent

Secure file storage armed with Magic Byte checking and Directory Traversal blocking.

storage = LocalStorageProvider(
    "./uploads",
    validators=[SafeMimeTypeValidator(["image/png", "image/jpeg"])]
)
Without: Insecure custom file streaming
BaseRepository🟢 Independent

Async CRUD, soft-delete restoration (restore/restore_multi), forced deletes, and keyset pagination.

class TaskRepo(BaseRepository[Task]):
    def __init__(self, db: AsyncSession):
        super().__init__(Task, db)
Without: Manual session.execute() queries
Pagination🟢 Independent

High-performance Cursor (Keyset) and Offset pagination with zero boilerplate.

params = CursorParams(size=20)
result = await repo.get_list(pagination=params)
Without: Manual offset/limit calculations
BaseService🟡 Composable

Domain business logic layer equipped with highly overridable pre/post action hooks.

class TaskService(BaseService[Task]):
    async def pre_create(self, schema):
        return {"slug": "slugified"}
Without: Manual procedural services
SearchEngine🟡 Composable

Dynamic queries with inverted operators (not_like, not_in), logical NOT groups, and field restrictions.

engine = SearchEngine(Task)
query = engine.build_query(req)
Without: Boilerplate conditional SQL logic
Zchema🟡 Composable

Dynamic field-level pruning. Interacts with raw FastAPI routers and standard schemas.

class TaskResponse(Zchema):
    __model__ = "tasks"
    title: str
    cost: float # hidden dynamically
Without: Writing multiple Pydantic outputs
BaseRouter🔴 Orchestrated

Generates 8 secure endpoints (including field-projected POST /lookup) with specificity sorting.

class TaskRouter(BaseRouter[TaskCreate, TaskUpdate]):
    model = Task
    create_schema = TaskCreate
    update_schema = TaskUpdate
    schema_out = TaskResponse
    lookup_schema = TaskResponse
    service = TaskService
Without: 8 redundant endpoint functions
Plugin System🔴 Orchestrated

Organize domains into isolated plugins with topological startup/shutdown ordering.

class TaskPlugin(Plugin):
    name = "tasks"
    dependencies = ["auth"]
    
    async def on_startup(self):
        await cache.warm()
Without: Manual app.on_event spaghetti
Total Overridability. No Framework Lock-In.
Need to customize how BaseRepository.create behaves? Just override it. Need specialized data transformations inside a service? Override pre_create or post_create. You are never boxed into framework assumptions.

Adopt Gradually. Scale Comfortably.

Start with plain FastAPI code. Introduce architectural helper layers one-by-one as your codebase expands. Each step is fully backward-compatible.

0Your existing FastAPI endpoint
@router.post("/tasks")
async def create_task(data: TaskCreate, db: AsyncSession = Depends(get_db)):
    task = Task(**data.model_dump())
    db.add(task)
    await db.commit()
    return task
Leave your legacy code exactly as it is. ZCore is backward-compatible.
1Add BaseRepository alone
class TaskRepo(BaseRepository[Task]):
    def __init__(self, db: AsyncSession):
        super().__init__(model=Task, db=db)

@router.post("/tasks")
async def create_task(data: TaskCreate, repo: Inject[TaskRepo]):
    return await repo.create(data)
One empty class. You now have async CRUD, search, and pagination.
2Now add BaseService (Optional)
class TaskService(BaseService[Task]):
    def __init__(self, repo: TaskRepo):
        super().__init__(model=Task, repository=repo)

    async def pre_create(self, schema: TaskCreate):
        return {"slug": slugify(schema.title)}
The pre_create interceptor hook runs, merges dynamic data, and persists safely.
3
Adopt Orchestrated Layers, or Stop Exactly Here.
You can use BaseRepository completely on its own forever. Or, opt to plug in Zchema for security constraints, UnitOfWork for database transactional safety, or BaseRouter to avoid endpoint boilerplates. No single step enforces the adoption of another.

When do I need this?

A transparent comparison. If the native route satisfies your architectural requirements, bypass the ZCore component.

When you want to...Use thisOr write this natively
Avoid writing redundant CRUD queries for every modelBaseRepositorySQLAlchemy queries
Orchestrate domain logic hooks before/after DB writesBaseServiceManual route logic
Prune schema attributes dynamically based on user rolesZchemaMultiple Pydantic models
Ensure multiple writes succeed atomically or fail completelyUnitOfWorksession.commit() blocks
Scaffold all 8 CRUD & lookup endpoints without route boilerplateBaseRouterIndividual route functions
Auto-wire repositories into services elegantlyInject[T]Depends() parameters
Execute background jobs with clean IoC & DB session isolationbackground_taskManual BackgroundTasks boilerplate
Dispatch events cleanly after a transaction commitsEventDispatcherManual listener triggers
Handle large datasets with high-performance cursor pagingPaginationManual offset/limit math
Structure domain modules with topological startup orderPlugin SystemSpaghetti app.on_event

Core Architecture Note: Every alternative in the right-hand column is completely valid, production-ready FastAPI code. ZCore simply streamlines the process, giving you the exact same outcomes with less code.

Interactive CLI.
Scaffold & Run in Seconds.

The built-in zc tool orchestrates your entire architecture — from interactive multi-database bootstrapping (SQLite, PostgreSQL, MySQL) with uv/pip virtualenvs, to granular 7-layer domain scaffolding, cryptographically secure secret generation, and cascading development servers with full Uvicorn option passthrough.

Explore CLI commands
$ pip install fastapi-zcore-framework[all]

$ zc init core_api --db postgres
✔ Scaffolding project with asyncpg driver & .venv
📁 core_api (main.py, .env, requirements.txt, .gitignore)

$ cd core_api && zc startapp order_management
✔ Modular App 'order_management' created
📄 models, schemas, repositories, services, routers, plugin, test_order_management

$ zc run
INFO: Uvicorn running on http://127.0.0.1:8000 (Reload: Enabled)
✔ ZCore kernel initialized with plugins & dialect logger
$ curl http://localhost:8000/tasks?schema=true

# Response JSON dynamically pruned according to requester scope:
{
"success": true,
"data": {
"title": "tasks",
"properties": {
"id": { "type": "string" },
"title": { "type": "string" }
# "cost" property is dynamically omitted due to security policies
}
}
}

Real-Time UI Generation
with ?schema=true

Avoid hardcoding your frontend forms. When appending ?schema=true to any ZCore route, the framework intercepts the request, dynamically inspects the authenticated user's permissions, prunes forbidden attributes, and yields the secure, tailored JSON Schema representation in real-time.

Directly build automated forms on Retool, Appsmith, or custom admin panels.
Eliminates data models mismatch between client and server fields.
Outputs metadata including restricted paths active in the user context.
✨ COMING SOON / ROADMAP

The Projection-Driven Admin Panel

We are conceptualizing a highly modular, lightning-fast administrative dashboard for FastAPI, natively powered by ZCore's projection-driven schema engine and context-shielded contracts.

Projection-based UI auto-generated from Zchema
Advanced reporting via SearchEngine
Code-free automated CRUD & action bindings
Real-time telemetry and async streaming
Active R&D Phase
We are actively researching this module to ensure zero performance compromise before releasing it.

Built to be Overridden.

Working defaults when you want speed.
Complete control when your business logic demands a customized path.

BaseRepository
create / create_multi
update_multi
restore / restore_multi
delete(force=True)
get_list / search
Override any DB action
BaseService
pre_create / post_create
pre_update / post_update
pre_restore / post_restore
post_delete(force=...)
Extend or block writes
BaseRouter
Override create_endpoint, lookup_endpoint, etc.
Add custom routes directly to router.router
Select active endpoints via RouteKey
Dynamic query schema exports (?schema=true)
Optionally bypass router entirely

Your FastAPI codebase. ZCore where it helps.

Enjoy development freedom. Standardize structures, protect endpoints, and manage atomic transactions only where you want to.

Created by Baseryn.