morethanadiagnosis-hub/backend/README.md
admin 078ed376eb feat(backend): implement 7-MVP FastAPI backend with all models and API stubs
Implements complete FastAPI backend infrastructure for MoreThanADiagnosis with:

Core Infrastructure:
- FastAPI application with CORS, error handling, health checks
- SQLAlchemy ORM with PostgreSQL support
- Pydantic configuration management
- Docker & Docker Compose for production deployment

Database Models (7 MVPs + Auth):
- User, Profile, Role, Consent (identity)
- RefreshToken, AuthAuditLog (authentication)
- ForumCategory, ForumThread, ForumPost, ForumReaction, ForumReport (forum)
- BlogPost (blog)
- PodcastEpisode (podcast)
- Resource (resources)
- TributeEntry (tribute)
- MerchProduct, Order, OrderItem (merch)

API Endpoints (Alphabetical MVPs):
- /api/v1/blog - Blog posts (list, get)
- /api/v1/forum - Categories, threads, posts, reactions, reports
- /api/v1/merch - Products, orders
- /api/v1/podcast - Episodes
- /api/v1/profiles - User profiles
- /api/v1/resources - Knowledge base
- /api/v1/tribute - Memorials
- /api/v1/health - Health checks

Configuration & Deployment:
- .env.example for configuration
- Dockerfile with multi-stage build
- docker-compose.yml for PostgreSQL + Redis + API
- Production-ready on nexus-vector with port 8000
- Non-root user, health checks, security best practices

Dependencies:
- FastAPI, SQLAlchemy, Pydantic
- PostgreSQL, Redis
- Testing (pytest), Security (passlib, python-jose)
- Full requirements.txt with 30+ packages

Status: Foundation complete, MVP endpoint stubs ready
Next: Database migrations, authentication implementation

Job ID: MTAD-IMPL-2025-11-18-CL

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-18 00:46:43 +00:00

350 lines
8.7 KiB
Markdown

# MoreThanADiagnosis Backend API
FastAPI backend for the MoreThanADiagnosis community platform.
**Job ID**: MTAD-IMPL-2025-11-18-CL
## 🏗 Architecture
- **Framework**: FastAPI with Python 3.11
- **Database**: PostgreSQL with SQLAlchemy ORM
- **Cache**: Redis
- **Deployment**: Docker + Docker Compose on nexus-vector
## 📦 Project Structure
```
backend/
├── app/
│ ├── api/v1/ # API endpoints for 7 MVPs
│ │ ├── blog.py
│ │ ├── forum.py
│ │ ├── merch.py
│ │ ├── podcast.py
│ │ ├── profiles.py
│ │ ├── resources.py
│ │ ├── tribute.py
│ │ └── health.py
│ ├── models/ # SQLAlchemy models (7 MVPs + auth)
│ ├── schemas/ # Pydantic schemas (TODO)
│ ├── services/ # Business logic (TODO)
│ ├── middleware/ # Custom middleware (TODO)
│ ├── utils/ # Utilities (TODO)
│ ├── config.py # Configuration
│ ├── database.py # Database setup
│ └── main.py # FastAPI app entry
├── migrations/ # Alembic migrations (TODO)
├── tests/ # Unit and integration tests (TODO)
├── Dockerfile # Container image
├── docker-compose.yml # Local development setup
├── requirements.txt # Python dependencies
└── .env.example # Environment variables template
```
## 🚀 Quick Start
### Prerequisites
- Docker & Docker Compose
- Python 3.11+ (for local development)
- PostgreSQL (if not using Docker)
### Local Development
1. **Set up environment**
```bash
cp .env.example .env
# Edit .env with your configuration
```
2. **Install dependencies**
```bash
pip install -r requirements.txt
```
3. **Start services**
```bash
docker-compose up -d
```
4. **Run migrations** (TODO)
```bash
alembic upgrade head
```
5. **Start API**
```bash
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```
6. **Access API**
- API: http://localhost:8000
- Docs: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
### Production Deployment (nexus-vector)
1. **Copy to nexus-vector**
```bash
scp -r backend/ admin@nexus-vector:/srv/containers/mtad-backend/
```
2. **Set production environment**
```bash
ssh admin@nexus-vector
cd /srv/containers/mtad-backend
cp .env.example .env
# Edit .env with production secrets
```
3. **Deploy with Docker Compose**
```bash
docker-compose up -d
```
4. **Verify health**
```bash
curl http://100.95.3.92:8000/health
```
## 📋 MVPs Implemented (Alphabetically)
### 1. Blog MVP
- List published blog posts
- Get individual posts by ID
- (TODO) Create, update, delete posts with authentication
### 2. Forum MVP
- List categories
- List threads per category
- List posts per thread
- (TODO) Create threads and posts with authentication
- (TODO) Emoji reactions and moderation reports
### 3. Merch MVP
- List products
- Get product details
- List orders
- (TODO) Create orders with authentication
### 4. Podcast MVP
- List episodes
- Get episode details
- (TODO) Upload and manage episodes
### 5. Profiles MVP
- Get user profile
- List public profiles
- (TODO) Update profile with authentication
### 6. Resources MVP
- List resources by access tier
- Get resources by ID or slug
- (TODO) Create resources with authorization
### 7. Tribute MVP
- List published tributes
- Get tribute details
- (TODO) Create tributes with authentication
## 🔐 Authentication & Authorization
**Status**: Specification approved (openspec/specs/authentication.md)
**TODO Implementation**:
- OAuth2/OIDC with PKCE
- JWT access tokens (15 min expiry)
- Refresh tokens with rotation (30 day expiry)
- RBAC: member, moderator, admin roles
- MFA (TOTP) support
- Password reset flow
- Account lockout protection
## 🗄 Database
**Status**: Schema specified (openspec/specs/data-model.md)
**Core Entities**:
- User (with email verification, MFA)
- Profile (display name, pseudonym, health journey)
- Forum (categories, threads, posts, reactions, reports)
- Blog (posts)
- Podcast (episodes)
- Resources (knowledge base)
- Tribute (memorials)
- Merch (products, orders)
- Consent (privacy compliance)
**Data Classification**:
- Public: Forum categories, public resources, published blog/podcast
- PII: Email, display names, shipping addresses, avatars
- PHI: Health journey, forum content (context-dependent), memorials
## 📊 API Endpoints
All endpoints use `/api/v1/` prefix.
### Blog
- `GET /api/v1/blog/` - List posts
- `GET /api/v1/blog/{post_id}` - Get post
### Forum
- `GET /api/v1/forum/categories` - List categories
- `GET /api/v1/forum/categories/{cat_id}/threads` - List threads
- `GET /api/v1/forum/threads/{thread_id}/posts` - List posts
### Merch
- `GET /api/v1/merch/products` - List products
- `GET /api/v1/merch/products/{id}` - Get product
- `GET /api/v1/merch/orders/{id}` - Get order
### Podcast
- `GET /api/v1/podcast/episodes` - List episodes
- `GET /api/v1/podcast/episodes/{id}` - Get episode
### Profiles
- `GET /api/v1/profiles/{user_id}` - Get profile
- `GET /api/v1/profiles/` - List public profiles
### Resources
- `GET /api/v1/resources/` - List resources
- `GET /api/v1/resources/{id}` - Get resource
- `GET /api/v1/resources/slug/{slug}` - Get by slug
### Tribute
- `GET /api/v1/tribute/` - List tributes
- `GET /api/v1/tribute/{id}` - Get tribute
### Health
- `GET /api/v1/health` - Health check
- `GET /api/v1/ready` - Readiness check
## 🧪 Testing
**Status**: Test infrastructure ready (pytest, pytest-asyncio)
**TODO**:
- Unit tests for models
- Integration tests for endpoints
- API contract tests
- Load testing
```bash
# Run tests
pytest tests/ -v
# Coverage report
pytest tests/ --cov=app --cov-report=html
```
## 🔄 Database Migrations
**Status**: Alembic configured, no migrations yet
```bash
# Create migration
alembic revision --autogenerate -m "Add forum tables"
# Apply migrations
alembic upgrade head
# Rollback
alembic downgrade -1
```
## 📝 Development Checklist
### Phase 1: Foundation (Current)
- [x] FastAPI project structure
- [x] Database models for all 7 MVPs
- [x] API endpoint stubs
- [x] Docker configuration
- [ ] Environment configuration finalization
- [ ] Database migrations
- [ ] Test infrastructure setup
### Phase 2: Authentication (Next)
- [ ] User registration/login
- [ ] Email verification
- [ ] Password hashing (Argon2)
- [ ] JWT token generation
- [ ] RBAC middleware
- [ ] MFA setup
### Phase 3: MVP Implementation
- [ ] Blog: Full CRUD with publishing
- [ ] Forum: Threading, moderation, reporting
- [ ] Merch: Shopping cart, checkout
- [ ] Podcast: Upload, streaming
- [ ] Profiles: User data management
- [ ] Resources: Knowledge base
- [ ] Tribute: Memorial management
### Phase 4: Integration & Deployment
- [ ] Frontend integration (Next.js web)
- [ ] Mobile integration (React Native/Expo)
- [ ] Production deployment
- [ ] Monitoring & alerting
- [ ] Performance optimization
## 🛠 Configuration
See `.env.example` for all available environment variables.
**Key Production Variables**:
```
ENV=production
DEBUG=false
DATABASE_URL=postgresql://user:pass@host:5432/db
SECRET_KEY=<generate-with-secrets>
CORS_ORIGINS=["https://morethanadiagnosis.com"]
```
## 📚 Documentation
- **OpenAPI/Swagger**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **Architecture Spec**: ../../openspec/specs/architecture.md
- **Data Model**: ../../openspec/specs/data-model.md
- **Authentication Spec**: ../../openspec/specs/authentication.md
- **Design System**: ../../openspec/specs/design-system.md
## 🚨 Known Issues
- [ ] Authentication not implemented yet
- [ ] Database migrations not created yet
- [ ] Request/response schemas not defined
- [ ] Error handling needs standardization
- [ ] Logging configuration needs refinement
- [ ] Rate limiting not configured
- [ ] CORS not finalized for production
## 📦 Dependencies
See `requirements.txt` for full list. Key dependencies:
- **fastapi** - Web framework
- **sqlalchemy** - ORM
- **alembic** - Migrations
- **pydantic** - Validation
- **passlib/argon2-cffi** - Password hashing
- **python-jose** - JWT
- **pytest** - Testing
- **uvicorn** - ASGI server
## 🤝 Contributing
1. Follow OpenSpec lifecycle (propose → review → apply → archive)
2. Ensure all code links to approved specs
3. Add tests for new features
4. Update documentation
5. Follow Python/FastAPI best practices
## 📄 License
Part of MoreThanADiagnosis community platform.
---
**Status**: Foundation complete, MVP implementation ready
**Next Action**: Database migrations + authentication implementation
**Job ID**: MTAD-IMPL-2025-11-18-CL