# FastAPI Health Template

[![CI](https://github.com/your-org/fastapi-health-template/actions/workflows/ci.yml/badge.svg)](https://github.com/your-org/fastapi-health-template/actions)
[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Stars](https://img.shields.io/github/stars/your-org/fastapi-health-template?style=social)](https://github.com/your-org/fastapi-health-template)

A production-ready FastAPI boilerplate for medical and healthcare applications.

## Why This Template?

Every healthcare app needs the same foundational pieces:

- **Medical disclaimer middleware** -- legal requirement, easy to forget
- **Drug/supplement data models** with JSONB ingredients and interaction severity levels
- **Interaction checking** -- the core feature users actually need
- **Device-based auth** -- no signup friction, just a UUID per device
- **HIPAA compliance checklist** -- so you know what to audit before launch
- **Redis caching** with category-specific TTLs (search: 24h, details: 3d, interactions: 7d, AI: 30d)
- **AI integration pattern** with concurrency control and response caching

This template gives you all of it. Clone, configure, build your features.

## Features

- **FastAPI** with async SQLAlchemy 2.0 and Pydantic v2
- **Device-based authentication** (X-Device-ID header, no passwords)
- **Drug & supplement models** with JSONB ingredient storage
- **Interaction check endpoint** with severity levels (critical/high/moderate/low/info)
- **Medical disclaimer middleware** on every response
- **Rate limiting middleware** (in-memory, swap to Redis for multi-instance)
- **Redis caching service** with tiered TTLs
- **AI service pattern** (OpenAI integration with semaphore limiting)
- **User medication cabinet** (CRUD, device-scoped)
- **Alembic migrations** (async-ready)
- **Docker Compose** setup (app + PostgreSQL 16 + Redis 7)
- **HIPAA compliance checklist** included
- **Full test suite** using pytest-asyncio + httpx

## Quick Start

```bash
# Clone
git clone https://github.com/your-org/fastapi-health-template.git
cd fastapi-health-template

# Start with Docker
cp .env.example .env
docker-compose up -d

# Run migrations
docker-compose exec app alembic upgrade head

# Visit the API docs
open http://localhost:8000/docs
```

### Without Docker

```bash
# Create virtual environment
python -m venv .venv
source .venv/bin/activate

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

# Start PostgreSQL and Redis (brew, apt, etc.)
# Configure .env with your connection strings

# Run migrations
alembic upgrade head

# Start the server
uvicorn app.main:app --reload
```

## Project Structure

```
app/
  main.py              # App factory, middleware setup, routes
  config.py            # Pydantic BaseSettings (env-based config)
  database.py          # Async SQLAlchemy engine + session
  dependencies.py      # Shared deps (device auth)
  middleware/
    disclaimer.py      # Adds X-Medical-Disclaimer header
    rate_limit.py      # In-memory rate limiter
    device_auth.py     # X-Device-ID validation
  models/
    drug.py            # Drug model (item_seq, ingredients JSONB)
    supplement.py      # Supplement model
    interaction.py     # Interaction model (severity, mechanism)
    user_cabinet.py    # User medication cabinet
  schemas/             # Pydantic request/response schemas
  api/v1/
    drugs.py           # GET /search, GET /{id}, GET /by-slug/{slug}
    supplements.py     # GET /search, GET /{id}
    interactions.py    # POST /check
    cabinet.py         # GET, POST, DELETE
  services/
    drug_service.py    # Business logic + caching
    interaction_service.py  # Pairwise interaction checking
    ai_service.py      # LLM integration pattern
    cache_service.py   # Redis with tiered TTLs
  utils/
    health_validators.py  # Medical content validators
tests/                 # pytest-asyncio test suite
docs/
  HIPAA_CHECKLIST.md   # Compliance checklist
  DEPLOYMENT.md        # Production deployment guide
```

## API Endpoints

| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | `/health` | Health check | Public |
| GET | `/api/v1/drugs/search?q=aspirin` | Search drugs | Public |
| GET | `/api/v1/drugs/{id}` | Drug detail | Public |
| GET | `/api/v1/drugs/by-slug/{slug}` | Drug detail by slug | Public |
| GET | `/api/v1/supplements/search?q=vitamin` | Search supplements | Public |
| GET | `/api/v1/supplements/{id}` | Supplement detail | Public |
| POST | `/api/v1/interactions/check` | Check interactions | Public |
| GET | `/api/v1/cabinet` | List cabinet items | Device ID |
| POST | `/api/v1/cabinet` | Add to cabinet | Device ID |
| DELETE | `/api/v1/cabinet/{id}` | Remove from cabinet | Device ID |

### Interaction Check Request

```json
POST /api/v1/interactions/check
{
  "item_ids": ["200001234", "200005678", "SUPP_001"]
}
```

### Interaction Check Response

```json
{
  "interactions": [
    {
      "item_a": "200001234",
      "item_b": "200005678",
      "severity": "high",
      "description": "Aspirin increases the anticoagulant effect of Warfarin.",
      "mechanism": "Platelet aggregation inhibition + protein binding displacement.",
      "recommendation": "Avoid combination or monitor INR closely.",
      "source": "DrugBank"
    }
  ],
  "total_checked": 3,
  "disclaimer": "This information is for reference only..."
}
```

## Configuration

All configuration is via environment variables (see `.env.example`):

| Variable | Default | Description |
|----------|---------|-------------|
| `DATABASE_URL` | `postgresql+asyncpg://...` | Async PostgreSQL URL |
| `REDIS_URL` | `redis://localhost:6379/0` | Redis connection |
| `CORS_ORIGINS` | `["http://localhost:3000"]` | Allowed CORS origins |
| `RATE_LIMIT_PER_MINUTE` | `60` | Per-client rate limit |
| `OPENAI_API_KEY` | (empty) | For AI explanations |
| `DISCLAIMER_TEXT` | (default text) | Medical disclaimer |

## HIPAA Compliance

This template includes a practical HIPAA checklist at `docs/HIPAA_CHECKLIST.md` covering:

- Data encryption (at rest + in transit)
- Access controls and audit logging
- Minimum necessary standard
- Device-level data storage preference
- De-identification guidelines
- Incident response planning

**This template is a starting point.** Consult a healthcare compliance professional before handling real patient data.

## Running Tests

```bash
pip install -e ".[dev]"
pytest -v --cov=app
```

Tests use an in-memory SQLite database (via aiosqlite) for speed and isolation.

## Deployment

See `docs/DEPLOYMENT.md` for full production deployment instructions including:

- Docker multi-stage build
- Nginx reverse proxy configuration
- PostgreSQL and Redis setup
- Scaling and monitoring recommendations

## Related Projects

Part of the [Pillright](https://github.com/MOB-sys) open-source healthcare ecosystem:

- [llm-medical-guard](https://github.com/MOB-sys/llm-medical-guard) — Safety guardrails for LLM medical content
- [drug-interaction-mcp](https://github.com/MOB-sys/drug-interaction-mcp) — MCP server for drug interaction checking
- [pharma-ai-agent](https://github.com/MOB-sys/pharma-ai-agent) — RAG-based drug information AI agent
- [awesome-drug-interactions](https://github.com/MOB-sys/awesome-drug-interactions) — Curated list of drug interaction resources
- [korean-pharma-data](https://github.com/MOB-sys/korean-pharma-data) — Korean pharmaceutical open data pipeline

## Legal Disclaimer

This software is provided as a development template. It does not constitute medical advice, diagnosis, or treatment. The authors and contributors are not responsible for any medical decisions made based on applications built with this template. Always ensure compliance with applicable healthcare regulations (HIPAA, GDPR, local laws) in your jurisdiction.

All drug interaction data must be sourced from authoritative databases and verified by qualified healthcare professionals.

## License

MIT -- see [LICENSE](LICENSE).
