/claude-kit:backend-repo-architecturefrom Claude Kit SDLC
Canonical backend repository structure for Python/FastAPI services — multi-mode entrypoint, app factory, ConnectionManager, BaseDao, flat vs versioned layout. Use when scaffolding or reorganizing a FastAPI service.
Ships in Claude Kit SDLC. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A canonical backend archetype for Python/FastAPI services, derived from real-world production systems.
All conventions below are derived from production Python/FastAPI services:
Entrypoint dispatcher (used by services B, C, D):
entrypoint.py at repo root dispatches on MODE environment variableserver, consumer, temporal_worker, worker, cron, webhook_serverserver mode runs uvicorn app.application:get_app --factory=Trueasyncio.run(service_main()) on the respective service moduleApplication factory (app/application.py):
get_app() -> FastAPI constructs the app instancedebug=settings.DEBUG, lifespan=lifespan, default_response_class=ORJSONResponseredirect_slashes=False to prevent ambiguous routingallow_origins, allow_credentials, allow_methods, allow_headersapi_router via app.include_router(api_router)/metrics for Prometheus)root_path for multi-deployment routingRouter aggregation (app/router.py or src/main.py):
api_router = APIRouter() aggregates all domain routers/_healthz and /_readyz/v1)DEPLOYMENT_NAME or SERVER_TYPE (multi-deployment variant)include_router(domain_router, prefix="/v1", tags=["Domain"])Custom routing (app/routing.py):
CustomRequestRoute(APIRoute) provides centralized request/response logging, timing, exception handlingResponseData.error() envelopeORJSONResponse with consistent error formatConnection management (app/connection.py):
ConnectionManager singleton (via __new__ or Singleton metaclass) manages AsyncEngine, scoped session factory, and Redis clientasync_scoped_session(sessionmaker(engine, expire_on_commit=False, class_=AsyncSession), scopefunc=current_task)ConnectionHandler per-request wrapper provides lazy .session and .redis propertiesset_tenant_context(tenant_id) and schema switching via set_schema_context(schema_name)get_connection_handler() dependency yields a handler and calls handler.close() on teardownLifetime hooks (app/lifetime.py):
@asynccontextmanager async def lifespan(app: FastAPI) manages startup/shutdownsetup_logging(), ConnectionManager(), Kafka producer, Temporal client, RedisBase DAO (app/dao.py):
BaseDao provides create, get_by_pk, update_by_pk, delete_by_pk, get_by_filter, get_paginated_response, bulk_insert, bulk_updateis_deleted and deleted_at attributes_execute_query(query) which rolls back on errorpage_size, page_number, sort_by, order_by with column validationDatabase base (app/database.py):
Base = declarative_base()class Base(DeclarativeBase): passBaseConfig pattern (config/settings.py or src/config/docker_config.py):
Settings(BaseSettings) with pydantic-settings for typed environment variablesSettings class, module-level settings = Settings()loaded_config = Settings() singleton, plus config_parser.py for configargparse-based YAML/env mergingDATABASE_URL, REDIS_URL, DEBUG, CORS_ORIGINS, KAFKA_BOOTSTRAP_SERVERS, TEMPORAL_HOST, etc.Domain layout: flat variant:
src/<domain>/ for many domain modulesrouter.py, service.py, dao.py, models.py, schemas.py, helper.py, constant.pyDomain layout: versioned variant:
<pkg>/<domain>/v1/{router,service,dao,models,schemas,helper,workflows}.pyMonorepo variant:
apps/ (api, orchestrator, workers, forwarders)packages/ (common, contracts, db, sdk)services/ (infra packages like Kafka, Temporal)application.py, router.py, lifetime.pyMulti-deployment variant:
SERVER_TYPE env var gates router inclusion (public/internal/platform/webhook)custom_openapi() rewrites paths with root_path like /service/{SERVER_TYPE}/product/featureinclude_router() based on loaded_config.SERVER_TYPEbackend/
├── entrypoint.py # MODE dispatcher (server/consumer/temporal_worker/cron) — OPTIONAL, omit for server-only
├── alembic/ # DB migrations
├── alembic.ini
├── pyproject.toml
├── Dockerfile
├── app/ # (or src/)
│ ├── application.py # get_app() factory
│ ├── router.py # api_router aggregation
│ ├── routing.py # CustomRequestRoute (optional but recommended)
│ ├── connection.py # ConnectionManager, ConnectionHandler, get_connection_handler
│ ├── dao.py # BaseDao
│ ├── database.py # Base (declarative base)
│ ├── lifetime.py # lifespan context manager
│ ├── main.py # uvicorn runner (server mode)
│ ├── telemetry.py # OpenTelemetry instrumentation (optional)
│ └── utils.py # ResponseData, helpers
├── config/
│ ├── settings.py # Settings(BaseSettings), settings singleton (pattern A)
│ ├── docker_config.py # Settings(BaseSettings), loaded_config singleton (pattern B)
│ ├── config_parser.py # configargparse (optional, pattern B)
│ └── logging.py # setup_logging
├── services/ # Kafka, Temporal config-driven infra (may be at root or under domain package)
│ ├── kafka/
│ │ ├── producer.py
│ │ └── consumer/
│ └── temporal/
└── <domain_pkg>/ # flat: src/<domain>/{router,service,dao,models,schemas}
└── <domain>/v1/ # versioned: <pkg>/<domain>/v1/{router,service,dao,models,schemas}
Flat domain example:
# src/product/router.py
from fastapi import APIRouter, Depends
from src.product.service import ProductService
from src.db.connection import get_connection_handler_for_app
product_router = APIRouter()
@product_router.get("/")
async def get_products(connection_handler = Depends(get_connection_handler_for_app)):
service = ProductService(connection_handler=connection_handler)
return await service.fetch_products(...)
Versioned domain example:
# app/identity/v1/router.py
from fastapi import APIRouter
from app.identity.v1.user.router import user_router
identity_v1_router = APIRouter(prefix="/identity")
identity_v1_router.include_router(user_router, prefix="/users")
Entrypoint MODE dispatch:
MODE = os.environ.get("MODE")
if MODE == "server":
from src.main import main as server_main
server_main() # uvicorn app.application:get_app --factory
elif MODE == "consumer":
from src.services.kafka.consumer.consumer import main as consumer_main
asyncio.run(consumer_main())
elif MODE == "temporal_worker":
from src.temporal.run import worker_main
asyncio.run(worker_main(worker_mode, temporal_queue))
elif MODE == "cron":
from src.crons.run import main as cron_main
asyncio.run(cron_main())
Application factory:
def get_app() -> FastAPI:
initialize_telemetry()
app = FastAPI(
debug=settings.DEBUG,
default_response_class=ORJSONResponse,
lifespan=lifespan,
docs_url="/docs" if settings.DEBUG else None,
)
app.include_router(api_router)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.CORS_ORIGINS,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization"],
)
return app
ConnectionHandler:
class ConnectionHandler:
def __init__(self):
self._session = None
self._redis = None
self._connection_manager = ConnectionManager()
@property
def session(self) -> AsyncSession:
if not self._session:
self._session = self._connection_manager.get_session_factory()()
return self._session
@property
def redis(self) -> Redis:
if not self._redis:
self._redis = self._connection_manager.get_redis()
return self._redis
async def close(self):
if self._session:
await self._session.close()
async def get_connection_handler() -> AsyncGenerator[ConnectionHandler, None]:
handler = ConnectionHandler()
try:
yield handler
finally:
await handler.close()
Lifespan:
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
setup_logging()
ConnectionManager() # init singleton
yield
shutdown_telemetry()
await ConnectionManager().close_connections()
Multi-deployment router gating:
api_router_prefix = APIRouter(prefix="/v1.0")
if loaded_config.SERVER_TYPE == "public":
api_router_prefix.include_router(shipment_router, tags=["Shipment v1.0"])
elif loaded_config.SERVER_TYPE == "internal":
api_router_prefix.include_router(shipment_router, tags=["Shipment v1.0"])
api_router_prefix.include_router(partner_config_router, tags=["Partner Config v1.0"])
elif loaded_config.SERVER_TYPE == "platform":
api_router_prefix.include_router(partner_config_router, tags=["Partner Config v1.0"])
elif loaded_config.SERVER_TYPE == "webhook":
api_router_prefix.include_router(clickpost_router, tags=["Click Post v1.0"])
if chains in application codeConnectionHandler via Depends(get_connection_handler)ConnectionManager singleton per process, never per-request engine creation__init__get_connection_handler dependency generator to guarantee teardown/v1 or similar version prefixCustomRequestRoute + ResponseData.error() for consistencyallow_origins, never use ["*"] in production@asynccontextmanager async def lifespan for startup/shutdown, never global init codesession.commit()selectinload() or joinedload() for relationships, profile queries with DB_ECHO=TrueWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ajyadav013/claude-kit --plugin claude-kit127 skills in this plugin
/accessibility-reviewUI accessibility (WCAG) review — keyboard operability, focus, ARIA semantics, color contrast, touch targets. Returns prioritized fixes. Distinct from performance/visual review./alembic-migrationsAlembic migration setup and patterns for async SQLAlchemy — async engine + run_sync in env.py, autogenerate, RLS/multi-tenant migrations. Use for alembic init, writing migrations, or debugging migration errors./anthropic-vertex-integrationClaude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry. Use when calling Claude via GCP Vertex AI (not direct Anthropic API)./api-and-interface-designStable API and interface design patterns. Use when designing REST/GraphQL endpoints, module boundaries, type contracts between modules or frontend/backend, or changing public interfaces./api-integrationWire the app to a backend API — data fetching, caching, error handling, loading states. Use when connecting to an endpoint, adding a fetch layer, or fixing API error and loading behaviour. React-query detail lives in tanstack-react-query-patterns./api-pagination-filtering-sortingHTTP query parameter conventions for pagination, filtering, sorting, and search with standardized response metadata. Use when designing list endpoints or building repositories that turn query params into SQL.Other plugins' skills for the same job