11 KiB
CLAUDE.md - API Backend
Service Overview
API Backend for Code of Conquest - The single source of truth for all business logic, game mechanics, and data operations.
Tech Stack: Flask + Appwrite + RQ + Redis + Replicate API (Llama-3/Claude models)
Port: 5000 (development), 5000 (production internal)
Location: /api
Architecture Role
This API backend is the single source of truth for all game logic:
- ✅ All business logic
- ✅ Data models and validation
- ✅ Database operations (Appwrite)
- ✅ Authentication & authorization
- ✅ Game mechanics calculations
- ✅ AI orchestration (all models via Replicate API)
- ✅ Background job processing (RQ)
What this service does NOT do:
- ❌ No UI rendering (that's
/public_weband/godot_client) - ❌ No direct user interaction (only via API endpoints)
Documentation Index
API Backend Documentation:
- API_REFERENCE.md - API endpoints and response formats
- DATA_MODELS.md - Character system, items, skills, effects
- GAME_SYSTEMS.md - Combat mechanics, marketplace, NPCs
- QUEST_SYSTEM.md - Quest mechanics and data structures
- STORY_PROGRESSION.md - Story progression system
- MULTIPLAYER.md - Multiplayer session backend logic
- API_TESTING.md - API testing guide with examples
- APPWRITE_SETUP.md - Database setup guide
- PHASE4_IMPLEMENTATION.md - Phase 4 detailed implementation tasks
Project-Wide Documentation:
- ../docs/ARCHITECTURE.md - System architecture overview
- ../docs/ROADMAP.md - Development roadmap and progress tracking
- ../docs/DEPLOYMENT.md - Deployment guide
- ../docs/WEB_VS_CLIENT_SYSTEMS.md - Feature distribution between frontends
Documentation Hierarchy:
/docs/= Project-wide roadmap, architecture, and cross-service documentation/api/docs/= API-specific implementation details (endpoints, data models, game systems)
Note: For overall project progress, always check
/docs/ROADMAP.md. Service-specific docs contain implementation details.
Development Guidelines
Project Structure
api/
├── app/ # Application code
│ ├── api/ # API endpoint blueprints
│ ├── models/ # Data models (dataclasses)
│ ├── services/ # Business logic & integrations
│ ├── utils/ # Utilities
│ ├── tasks/ # Background jobs (RQ)
│ ├── ai/ # AI integration
│ ├── game_logic/ # Game mechanics
│ └── data/ # Game data (YAML)
├── config/ # Configuration files
├── tests/ # Test suite
├── scripts/ # Utility scripts
└── docs/ # API documentation
Coding Standards
Style & Structure
- Prefer longer, explicit code over compact one-liners
- Always include docstrings for functions/classes + inline comments
- Strongly prefer OOP-style code (classes over functional/nested functions)
- Strong typing throughout (dataclasses, TypedDict, Enums, type hints)
- Value future-proofing and expanded usage insights
Data Design
- Use dataclasses for internal data modeling
- Typed JSON structures
- Functions return fully typed objects (no loose dicts)
- Snapshot files in JSON or YAML
- Human-readable fields (e.g.,
scan_duration)
Logging
- Use structlog (pip package)
- Setup logging at app start:
logger = structlog.get_logger(__file__)
Preferred Pip Packages
- API/Web Server: Flask
- HTTP: Requests
- Logging: Structlog
- Job Queue: RQ
- Testing: Pytest
API Design Standards
RESTful Conventions:
- Use proper HTTP methods (GET, POST, PUT, DELETE)
- Resource-based URLs:
/api/v1/characters, not/api/v1/get_character - Versioning:
/api/v1/...
Standardized Response Format:
{
"app": "Code of Conquest API",
"version": "0.1.0",
"status": 200,
"timestamp": "2025-01-15T10:30:00Z",
"request_id": "optional-request-id",
"result": {
"data": "..."
},
"error": null,
"meta": {}
}
Error Responses:
{
"app": "Code of Conquest API",
"version": "0.1.0",
"status": 400,
"timestamp": "2025-01-15T10:30:00Z",
"result": null,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid character name",
"details": {
"field": "name",
"issue": "Name must be between 3 and 50 characters"
}
}
}
Error Handling
- Custom exception classes for domain-specific errors
- Consistent error response formats (use
app.utils.response) - Logging severity levels (ERROR vs WARNING)
- Never expose internal errors to clients (sanitize stack traces)
Security Standards
Authentication & Authorization
- Use Appwrite Auth for user management
- HTTP-only cookies for session storage
- Session validation on every protected API call
- User ID verification (users can only access their own data)
- Use
@require_authdecorator for protected endpoints
Input Validation
- Validate ALL JSON payloads against schemas
- Sanitize user inputs (character names, chat messages)
- Prevent injection attacks (SQL, NoSQL, command injection)
- Use bleach for HTML sanitization
Rate Limiting
- AI endpoint limits based on subscription tier
- Use Flask-Limiter with Redis backend
- Configure limits in
config/*.yaml
API Security
- CORS properly configured (only allow frontend domains)
- API keys stored in environment variables (never in code)
- Appwrite permissions set correctly on all collections
- HTTPS only in production
Cost Control (AI)
- Daily limits on AI calls per tier
- Max tokens per request type
- Cost logging for analytics and alerts
- Graceful degradation if limits exceeded
Configuration
- Environment-specific configs in
/config/*.yamldevelopment.yaml- Local dev settingsproduction.yaml- Production settings
.envfor secrets (never committed)- Maintain
.env.examplefor documentation - Typed config loaders using dataclasses
- Validation on startup
Testing Standards
Unit Tests (Pytest):
- Test all models, services, game logic
- Test files in
/tests - Run with:
pytest - Coverage:
pytest --cov=app tests/
Integration Tests:
- Test API endpoints end-to-end
- Use test database/fixtures
- Example:
tests/test_api_characters_integration.py
API Testing:
- Maintain
docs/API_TESTING.mdwith curl/httpie examples - Document expected responses
- Test all endpoints manually before commit
Dependency Management
- Use
requirements.txtin/apidirectory - Use virtual environment:
python3 -m venv venv - Pin versions to version ranges
- Activate venv before running:
source venv/bin/activate
Background Jobs (RQ)
Queue Types:
ai_tasks- AI narrative generationcombat_tasks- Combat processingmarketplace_tasks- Auction cleanup, periodic tasks
Job Implementation:
- Define jobs in
app/tasks/ - Use
@jobdecorator from RQ - Jobs should be idempotent (safe to retry)
- Log job start, completion, errors
Running Workers:
rq worker ai_tasks combat_tasks marketplace_tasks --url redis://localhost:6379
Workflow for API Development
When implementing new API features:
- Start with models - Define dataclasses in
app/models/ - Write tests - TDD approach (test first, then implement)
- Implement service - Business logic in
app/services/ - Create endpoint - API blueprint in
app/api/ - Test manually - Use curl/httpie, update
docs/API_TESTING.md - Security review - Check auth, validation, rate limiting
- Document - Update
docs/API_REFERENCE.md
Example Flow:
# 1. Create model
# app/models/quest.py - Define Quest dataclass
# 2. Write test
# tests/test_quest.py - Test quest creation, validation
# 3. Implement service
# app/services/quest_service.py - Quest CRUD operations
# 4. Create endpoint
# app/api/quests.py - REST endpoints
# 5. Test
curl -X POST http://localhost:5000/api/v1/quests \
-H "Content-Type: application/json" \
-d '{"title": "Find the Ancient Relic"}'
# 6. Document
# Update docs/API_REFERENCE.md and docs/API_TESTING.md
Running the API Backend
Development
Prerequisites:
- Python 3.11+
- Redis running (via Docker Compose)
- Appwrite instance configured
Setup:
cd api
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your credentials
Initialize Database:
python scripts/init_database.py
Run Development Server:
# Terminal 1: Redis
docker-compose up
# Terminal 2: API Server
source venv/bin/activate
export FLASK_ENV=development
python wsgi.py # → http://localhost:5000
# Terminal 3: RQ Worker (optional)
source venv/bin/activate
rq worker ai_tasks --url redis://localhost:6379
Production
Run with Gunicorn:
gunicorn --bind 0.0.0.0:5000 --workers 4 wsgi:app
Environment Variables:
FLASK_ENV=production
APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
APPWRITE_PROJECT_ID=...
APPWRITE_API_KEY=...
APPWRITE_DATABASE_ID=...
ANTHROPIC_API_KEY=...
REPLICATE_API_TOKEN=...
REDIS_URL=redis://redis:6379
SECRET_KEY=...
Git Standards
Commit Messages:
- Use conventional commit format:
feat:,fix:,docs:,refactor:, etc. - Examples:
feat(api): add quest endpointsfix(models): character stat calculation bugdocs(api): update API_REFERENCE with quest endpoints
Branch Strategy:
- Branch off
devfor features - Merge back to
devfor testing - Promote to
masterfor production
Notes for Claude Code
When working on the API backend:
- Business logic lives here - This is the single source of truth
- No UI code - Don't create templates or frontend code in this service
- Security first - Validate inputs, check permissions, sanitize outputs
- Cost conscious - Monitor AI usage, implement limits
- Test thoroughly - Use pytest, write integration tests
- Document as you go - Update API_REFERENCE.md and API_TESTING.md
- Think about frontends - Design endpoints that work for both web and Godot clients
Remember:
- Developer has strong security expertise (don't compromise security for convenience)
- Developer has extensive infrastructure experience (focus on application logic)
- This API serves multiple frontends (web and Godot) - keep it generic