Skip to main content

A Python backend framework that brings a Spring Boot-style developer experience while respecting Python's philosophy.

Project description

XIME Framework

Spring Boot-style developer experience for Python - without betraying Python's philosophy.

PyPI version Python License: MIT

Documentation · Examples


XIME is a convention layer for Python microservices. It sits on top of FastAPI, SQLAlchemy, and gRPC - providing automatic dependency injection, startup-time graph validation, and architectural guardrails so you can focus on business logic instead of wiring.

# Before XIME - wire everything manually
container.user_service = providers.Singleton(
    UserService,
    repository=container.user_repository,
    transaction=container.transaction_manager,
)

# With XIME - just write your class
class UserService:
    def __init__(
        self,
        repository: UserRepository,
        transaction: TransactionManager,
    ):
        self.repository = repository
        self.transaction = transaction

XIME reads your type hints, scans your packages, builds the dependency graph, validates it at startup, and wires everything together - automatically.


Why XIME?

Python has excellent libraries for HTTP, databases, and serialization. What it lacks is a convention layer that:

  • Automatically discovers and wires dependencies from constructor type hints
  • Enforces architectural boundaries through directory structure
  • Validates the dependency graph at startup - not at runtime when a user hits an endpoint
  • Provides a consistent structure for Clean Architecture / DDD / Modular Monolith projects

XIME fills that gap. It does not replace FastAPI or SQLAlchemy - it makes them easier to use at scale.


Why not dependency-injector, injector, or lagom?

These are solid libraries. XIME used to lean on dependency-injector for its singleton storage layer, but as of 0.6 the registry is hand-rolled (a plain dict keyed by the class object), so XIME has no third-party DI dependency at all. The difference is scope:

dependency-injector / injector lagom XIME
Auto-scan packages by directory No - manual wiring required No Yes
Startup-time graph validation No Partial Yes - cycles, missing impl, ambiguous bindings
Code-first gRPC generation No No Yes
Web framework integration No No Yes - controllers, middleware, lifecycle
Explicit transaction management No No Yes - async with self.transaction():
Designed for microservice structure No No Yes

If you only need DI, use dependency-injector or lagom. If you want a full convention layer that wires DI, HTTP, gRPC, transactions, and lifecycle together - use XIME.


How It Works

Application Code
      ↓
   XIME Core          ← scanning, DI, lifecycle, config
      ↓
  DI Container        ← core/container, built-in
      ↓
Python Objects

XIME's startup pipeline:

  1. Load framework configuration (config/dependency.py)
  2. Load runtime configuration (resources/application.yml)
  3. Scan declared packages
  4. Resolve type hints
  5. Build dependency graph
  6. Validate graph - detect cycles, missing implementations, ambiguous bindings
  7. Create singletons
  8. Start adapters (FastAPI, gRPC, ...)

If anything is wrong, the app fails immediately at startup with a clear error - not later in production.


Installation

pip install xime

Adapters and starters are optional - install only what you need:

pip install "xime[web]"          # Uvicorn ASGI server
pip install "xime[sqlalchemy]"   # async DB sessions + transactions
pip install "xime[jwt]"          # JWT authentication
pip install "xime[scheduler]"    # cron-style task scheduling
pip install "xime[redis]"        # Redis client + cache backend
pip install "xime[grpc]"         # gRPC adapter (code-first)
pip install "xime[socket]"       # Unix domain socket IPC
pip install "xime[mqtt]"         # MQTT adapter (pub/sub + RPC over MQTT v5)
pip install "xime[s3]"           # S3 / MinIO storage backend
pip install "xime[all]"          # everything above

Requires Python 3.12+.


Quick Start

1. Define a controller - a plain class; methods map to routes.

# app/api/rest/user_controller.py
from xime.adapters.web.routing import get

class UserController:
    prefix = "/users"

    def __init__(self, use_case: GetUserUseCase) -> None:
        self._use_case = use_case

    @get("/{user_id}", response_model=UserResponse)
    async def get_user(self, user_id: int) -> UserResponse:
        return await self._use_case.execute(user_id)

2. Configure dependency injection - declare which packages to scan and bind interfaces to implementations.

# app/config/dependency.py
from xime import BindingConfig

dependency = BindingConfig()
dependency.scan("application.usecase", "infrastructure.repository")
dependency.bind({UserRepository: JpaUserRepository})

3. Bootstrap the application.

# app/main.py
from xime import Application
from xime.adapters.web import WebAdapter

app = Application()
app.use(WebAdapter())
app.run()

4. Run it.

python app/main.py
Going further - multiple protocols & servers
# REST + gRPC simultaneously
from xime import Application
from xime.adapters.web import WebAdapter
from xime.adapters.grpc import GrpcAdapter

app = Application()
app.use(WebAdapter())
app.use(GrpcAdapter())
app.run()
# Multiple servers in one process (public API + internal admin)
from xime import Application
from xime.adapters.web import WebAdapter

app = Application()
app.use(WebAdapter())                              # server_id="default", port from application.yml
app.use(WebAdapter("admin", "127.0.0.1", 8081))   # server_id="admin", explicit host/port
app.run()

📦 Example Projects

The best way to learn XIME is to read real code. These open-source projects are built on the framework - clone them, run them, and use them as references for structuring your own service:

Project What it demonstrates Good for
xime-shop-example An e-commerce demo using a straightforward layered architecture. 🟢 Getting started
data-service A production-grade microservice: Hexagonal / DDD, gRPC, SQLAlchemy, multi-tenant sharding. The most complete reference. 🔵 Real-world patterns
notification-service An async, IO-bound notification microservice with event-driven patterns. 🔵 Async & events
xime-grpc-socket-example One app serving gRPC (code-first, dynamic mTLS) and Unix Domain Sockets side by side, with shared @command / @stream contracts and different security models. 🟣 Multi-transport

New to XIME? Start with xime-shop-example for the fundamentals, then study data-service for full Hexagonal/DDD patterns at production scale. To see one app speak gRPC and sockets at once, read xime-grpc-socket-example.


Features

Feature Description
Constructor Injection Declare dependencies as constructor params - XIME wires them
Directory-Driven DI Package location determines component role - no annotations
Interface Binding Explicit Protocol → implementation mapping, validated at startup
Dynamic Binding Bind one Protocol to several impls (a tuple) and swap them app-wide at runtime via Switcher; off by default, consumers keep their code
Fail Fast Circular deps, missing implementations, ambiguous bindings → startup error
Lifecycle Hooks PostConstruct, PreDestroy for managed startup/shutdown
Initialization Order dependency.order([A, B, C]) - control post_construct() execution order across independent classes
Multi-Server Multiple WebAdapter / GrpcAdapter / SocketAdapter per process, each with its own server_id
Event Bus Internal pub/sub for decoupled domain events
Request Context Per-request data via ContextVar, set by adapters
Security Context AuthenticationManager, AuthorizationManager in core
Two-Layer Config Framework config (Python) + Runtime config (YAML)
Transaction API Explicit async with self.transaction(): - no hidden AOP
Class-Based Controllers Controllers are DI singletons, methods map to routes
Code-First gRPC Write Python DTOs, XIME generates .proto + stubs; field-number stability via lock file
gRPC Client SDK Generate a typed Pydantic client from .proto, inject via DI; deadlines, typed errors, automatic retry
Dynamic mTLS Certificate rotation without restart for both inbound servers and outbound clients
Peer Identity gRPC reads the verified client-cert CN into request context; current_caller() exposes it (fail-soft)
Socket Adapter Unix Domain Socket IPC for same-host Native Engine calls (Linux); @command / @stream
MQTT Adapter Message-driven transport for IoT/embedded: @subscribe (pub/sub) + @rpc (request/reply over MQTT v5); auto-reconnect; bounded concurrency
File Storage Backend-neutral StorageService (local filesystem / S3 / MinIO); bytes + streaming APIs; HTTP Range download and chunked upload helpers

Starters

Optional modules, similar to spring-boot-starter-*:

Starter What it provides Status
xime.starters.sqlalchemy Async DB session, SqlAlchemyTransactionManager, CrudRepository (built-in CRUD) ✅ Implemented
xime.starters.jwt JWT signing, verification, middleware ✅ Implemented
xime.starters.scheduler Cron-style task scheduling ✅ Implemented
xime.starters.cache CacheService abstraction (backend-neutral) ✅ Implemented
xime.starters.redis Async Redis client + CacheService backend ✅ Implemented
xime.starters.storage StorageService abstraction (object/blob store) ✅ Implemented
xime.starters.localfs Local filesystem StorageService backend ✅ Implemented
xime.starters.s3 S3 / MinIO StorageService backend (multipart, presigned URL) ✅ Implemented

Design Principles

  • Explicit over implicit - binding, routing, config are always declared, never auto-discovered by magic
  • Constructor injection only - no @inject, no field injection, no @autowired
  • No annotations for roles - @service, @repository, @component do not exist; directory determines role
  • Fail fast - errors surface at startup, not at runtime
  • Thin wrapper - XIME does not rewrite FastAPI, SQLAlchemy, or gRPC; it orchestrates them

Project Status

XIME is in active development. The following are implemented: core DI (hand-rolled singleton registry, no third-party DI dependency) with dynamic interface binding (one Protocol → many impls, swapped at runtime), lifecycle, event bus, security context, configuration, JWT starter (with audience/issuer enforcement), scheduler starter, SQLAlchemy starter, Cache + Redis starters, Storage starter (local filesystem + S3/MinIO) with HTTP file streaming (Range download, chunked upload), Web adapter (FastAPI + routing, pure-ASGI request-context & JWT middleware, custom middleware & exception handlers, DI/config-aware middleware via Inject/FromConfig markers + first-class configure_cors), gRPC adapter (proto-first + code-first, dynamic mTLS), gRPC client SDK (typed, DI-injected, deadlines + typed errors + automatic retry), Socket adapter (Unix Domain Socket IPC), MQTT adapter (pub/sub + RPC over MQTT v5), multi-server support, and initialization order (dependency.order()). WebSocket support is partial.

The core is covered by 1090+ tests.

See the CHANGELOG for release history.


Documentation

Document Description
Getting Started First app in 5 minutes
Architecture How XIME is structured internally
Core Concepts DI, interface binding, scopes
Configuration Framework config + runtime YAML
Routing Class-based controllers, route decorators
Transaction Explicit transaction management
Code-First gRPC Generate .proto from Python DTOs; field-number stability; xime grpc generate/check; dynamic mTLS
gRPC Client SDK Generate a typed client SDK; inject it via DI; deadlines, typed errors, retry, dynamic mTLS
Socket Adapter Unix Domain Socket IPC for same-host Native Engine calls
MQTT Adapter Message-driven pub/sub + RPC over MQTT v5 for IoT/embedded
File Storage StorageService (local / S3 / MinIO) + HTTP Range download & chunked upload
Starters SQLAlchemy, JWT, Scheduler, Cache, Redis, Storage
Testing DI overrides, fakes, test utilities
Contributing How to contribute, roadmap

Contributing

XIME is a solo project that needs community help to grow. There is still ground to cover: completing WebSocket support, CLI scaffolding, testing utilities, and more.

Ways to contribute:

  • Read the architecture docs to understand the design
  • Pick an open area from the roadmap
  • Open an issue to discuss a feature or bug
  • Submit a pull request

Please read CONTRIBUTING before opening a PR.


License

Released under the MIT License.

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

xime-0.6.1.tar.gz (170.9 kB view details)

Uploaded Source

Built Distribution

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

xime-0.6.1-py3-none-any.whl (246.0 kB view details)

Uploaded Python 3

File details

Details for the file xime-0.6.1.tar.gz.

File metadata

  • Download URL: xime-0.6.1.tar.gz
  • Upload date:
  • Size: 170.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for xime-0.6.1.tar.gz
Algorithm Hash digest
SHA256 38acf2637cff23385763fa109aa4a0534cb681fa0e9f91d368fc69ea871d5a66
MD5 a972aecfdbc3dba3161eee12c45df389
BLAKE2b-256 bee6c09d56a65ac0e9ed2652b598cd66cf1c8443163f5011e634b40473d9e745

See more details on using hashes here.

File details

Details for the file xime-0.6.1-py3-none-any.whl.

File metadata

  • Download URL: xime-0.6.1-py3-none-any.whl
  • Upload date:
  • Size: 246.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for xime-0.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 714712623bc60aa661fb5da56a7ab820ed2a584962fa019c2d54179c3683ebdb
MD5 ee51b224e055a63a4618884bf9b5b3e5
BLAKE2b-256 e6e235326a954182c93bc289d5302023b109549a9940d42e6337c4010ed0063a

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