Skip to main content

Backend Common Package

A shared utilities package for Python backend microservices, providing standardized components for authentication, HTTP communication, database management, and more.

Features

✅ Common Exceptions - Standardized error handling with correlation tracking
✅ Authentication & Authorization - JWT-based auth with FastAPI dependencies
✅ HTTP Client Utilities - Robust HTTP clients with retry logic and service auth
✅ Database Management - SQLAlchemy async session handling with health checks
✅ Middleware Components - Logging, correlation IDs, and authentication middleware
✅ Health Monitoring - Service health checks and dependency monitoring
✅ Configuration Management - Pydantic-based settings with environment support
✅ Utility Functions - Time handling, validation, and common operations

Installation

# Install from PyPI (once published)
pip install backend-common

# Or using uv
uv add backend-common

# Install from git repository
pip install git+https://github.com/your-org/backend-common.git

Quick Start

1. Basic FastAPI Integration

from fastapi import FastAPI, Depends
from backend_common.middleware import CorrelationMiddleware, LoggingMiddleware
from backend_common.auth.dependencies import require_auth
from backend_common.exceptions import NotFoundError
from backend_common.models import HealthResponse

app = FastAPI()

# Add middleware
app.add_middleware(CorrelationMiddleware)
app.add_middleware(LoggingMiddleware)

@app.get("/protected", dependencies=[Depends(require_auth())])
async def protected_endpoint():
    return {"message": "This endpoint requires authentication"}

@app.get("/health", response_model=HealthResponse)
async def health_check():
    return HealthResponse.healthy("my-service")

2. Database Setup

from backend_common.database import DatabaseManager, set_database_manager
from backend_common.config import ServiceConfig

# Initialize configuration
config = ServiceConfig(
    service_name="my-service",
    database_url="postgresql+asyncpg://user:pass@localhost/db"
)

# Setup database manager
db_manager = DatabaseManager(config.database_url)
set_database_manager(db_manager)

# Use in endpoints
from backend_common.database import get_db_session

@app.get("/users")
async def get_users(db: AsyncSession = Depends(get_db_session)):
    # Use database session
    pass

3. Service Communication

from backend_common.http_client import ServiceClient
from backend_common.auth.manager import JWTAuthManager

# Setup service client
auth_manager = JWTAuthManager(secret_key="your-secret")
client = ServiceClient(
    service_name="my-service",
    base_url="http://other-service:8000",
    auth_manager=auth_manager
)

# Make authenticated requests
async with client:
    response = await client.get("/api/data")
    data = response.json()

Configuration

The package uses Pydantic settings for configuration management:

from backend_common.config import ServiceConfig

config = ServiceConfig(
    service_name="my-service",
    database_url="postgresql+asyncpg://...",
    jwt_secret_key="your-secret-key",
    environment="production"
)

Environment variables are automatically loaded from .env files or system environment.

Exception Handling

Standardized exceptions with correlation tracking:

from backend_common.exceptions import NotFoundError, ValidationError

# Business logic exceptions
raise NotFoundError("User", "123")
raise ValidationError("email", "invalid@", "Must be valid email")

# HTTP exceptions  
raise UnauthorizedError("Invalid token")
raise ServiceUnavailableError("user-service", "Connection timeout")

Health Checks

Built-in health monitoring for services and dependencies:

from backend_common.http_client import HealthChecker
from backend_common.models import HealthStatus

# Setup health checker
health_checker = HealthChecker({
    "database": "http://localhost:5432/health",
    "redis": "http://localhost:6379/health"
})

await health_checker.start_monitoring()

# Check service health
status = health_checker.get_service_status("database")
is_healthy = status.status == HealthStatus.HEALTHY

Development

Setup Development Environment

# Clone repository
git clone https://github.com/your-org/backend-common.git
cd backend-common

# Install dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black src/
isort src/

# Type checking
mypy src/

Publishing to PyPI

# Build package
python -m build

# Upload to PyPI
python -m twine upload dist/*

License

MIT License - see LICENSE file for details.

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

Support

For issues and questions, please use the GitHub issue tracker.

Metadata

Release files for backend-common-kato 0.0.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for backend-common-kato 0.0.6
File Size Uploaded Provenance
backend_common_kato-0.0.6.tar.gz 103.1 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for backend-common-kato 0.0.6
File Interpreter ABI Platform
backend_common_kato-0.0.6-py3-none-any.whl Python 3 none any Details

Total release size: 137.2 kB

Release files / backend_common_kato-0.0.6.tar.gz

Download URL backend_common_kato-0.0.6.tar.gz
Size 103.1 kB
Tags Source
SHA-256 checksum
How to use checksums
7999b2b1a36a64d578269a2bbe59633888604b7e14db202b6b170ee1f7aa1ee4
BLAKE2b-256 checksum
How to use checksums
5a2b0f6fd2334aef03409a3c0c7176ad563b667aab3a3f5390794e72768e36a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.0

Release files / backend_common_kato-0.0.6-py3-none-any.whl

Download URL backend_common_kato-0.0.6-py3-none-any.whl
Size 34.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b90ae3dacb929fb57ca07717c982cb9c686c7af2003b8f899c20201fe4bcd3eb
BLAKE2b-256 checksum
How to use checksums
57137d7b42b8843c5fefa7946aa3c3971ff9a0a0606c58a8ed198cc25775278d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.0

Security for backend-common-kato 0.0.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page