# {{ project.name }}

A high-performance microservice built with the Gobstopper framework.

## 🚀 Features

- **RESTful API**: Complete CRUD operations with proper HTTP methods
- **Authentication & Authorization**: JWT-based auth with role-based access control
- **Rate Limiting**: Built-in request rate limiting and throttling
- **Health Monitoring**: Comprehensive health checks and metrics
- **Background Tasks**: Async task processing with priority queues
- **Webhook Support**: Secure webhook handling with signature verification
- **Auto-scaling Ready**: Stateless design for horizontal scaling
- **Observability**: Structured logging, metrics, and distributed tracing
- **Data Validation**: Request/response validation with detailed error messages
- **Batch Operations**: Efficient bulk operations support

## 📁 Project Structure

```
{{ project.name }}/
├── services/            # Core business logic
├── models/              # Data models and schemas
├── utils/               # Utilities (auth, metrics, logging)
├── tasks/               # Background tasks
├── tests/               # Test suite
├── config/              # Configuration management
└── deploy/              # Deployment configurations
```

## 🛠️ Setup

### Requirements

- Python 3.11+
- PostgreSQL/MySQL (for data persistence)
- Redis (for caching and sessions)
- Gobstopper framework

### Installation

```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Copy environment variables
cp .env.example .env
# Edit .env with your configuration
```

### Configuration

Key environment variables:

```bash
# Service Configuration
SERVICE_VERSION=1.0.0
ENVIRONMENT=development
DEBUG=true

# Database
DATABASE_URL=postgresql://user:pass@localhost/{{ project.python_module }}

# Authentication
SECRET_KEY=your-secret-key-here
REQUIRE_AUTH=true

# Rate Limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60

# Features
ENABLE_SYNC=true
ENABLE_NOTIFICATIONS=true
VERIFY_WEBHOOK_SIGNATURES=true
```

## 🚀 Running the Service

### Development

```bash
# Run with hot reload
granian --interface rsgi --reload app:app

# Service will be available at http://localhost:8000
```

### Production

```bash
# Run with multiple workers
granian --interface rsgi --workers 4 --host 0.0.0.0 --port 8000 app:app

# Or using Docker
docker build -t {{ project.name }}:latest .
docker run -p 8000:8000 --env-file .env {{ project.name }}:latest
```

## 📚 API Documentation

### Health & Monitoring

- `GET /health` - Service health check
- `GET /metrics` - Prometheus-compatible metrics
- `GET /info` - Service information and metadata

### Core Resources

- `GET /api/v1/{{ project.python_module }}` - List resources
- `GET /api/v1/{{ project.python_module }}/{id}` - Get specific resource
- `POST /api/v1/{{ project.python_module }}` - Create resource
- `PUT /api/v1/{{ project.python_module }}/{id}` - Update resource
- `DELETE /api/v1/{{ project.python_module }}/{id}` - Delete resource
- `POST /api/v1/{{ project.python_module }}/batch` - Batch operations

### Webhooks

- `POST /webhooks/{source}` - Receive webhooks from external services

### Admin Operations

- `GET /admin/stats` - Administrative statistics
- `POST /admin/maintenance` - Trigger maintenance tasks

## 🔐 Authentication

The service supports JWT-based authentication:

### Getting an Access Token

```bash
curl -X POST http://localhost:8000/auth/token \
  -H "Content-Type: application/json" \
  -d '{"username": "user", "password": "pass"}'
```

### Using the Token

```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:8000/api/v1/{{ project.python_module }}
```

## 📊 API Examples

### Create a Resource

```bash
curl -X POST http://localhost:8000/api/v1/{{ project.python_module }} \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "name": "Example Resource",
    "description": "This is an example",
    "tags": ["example", "demo"]
  }'
```

### List Resources with Filtering

```bash
# Basic listing
curl "http://localhost:8000/api/v1/{{ project.python_module }}"

# With pagination
curl "http://localhost:8000/api/v1/{{ project.python_module }}?page=2&limit=10"

# With filtering
curl "http://localhost:8000/api/v1/{{ project.python_module }}?status=active&tag=production"
```

### Batch Operations

```bash
curl -X POST http://localhost:8000/api/v1/{{ project.python_module }}/batch \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -d '{
    "operation": "update",
    "resource_ids": ["id1", "id2", "id3"],
    "data": {"status": "archived"}
  }'
```

## 🔧 Background Tasks

The service includes several types of background tasks:

### Data Synchronization
- Sync data between services
- Handle eventual consistency
- Retry failed operations

### Notifications
- Send email/SMS notifications
- Push notifications to mobile apps
- Webhook notifications to external services

### Maintenance
- Clean up old data
- Optimize database indexes
- Generate reports

### Monitor Tasks

```bash
# View task status
curl "http://localhost:8000/admin/tasks/TASK_ID" \
  -H "Authorization: Bearer ADMIN_TOKEN"
```

## 🌐 Integration Examples

### Webhook Integration

```python
# Example webhook handler for external service integration
@app.post("/webhooks/external-service")
async def handle_external_webhook(request):
    webhook_data = await request.get_json()
    
    # Process webhook asynchronously
    await app.add_background_task(
        "process_webhook",
        webhook_data=webhook_data,
        source="external-service"
    )
    
    return {"status": "received"}
```

### Service-to-Service Communication

```python
import aiohttp

async def call_another_service():
    async with aiohttp.ClientSession() as session:
        async with session.get(
            "http://other-service/api/data",
            headers={"Authorization": f"Bearer {service_token}"}
        ) as response:
            return await response.json()
```

## 📈 Monitoring & Observability

### Health Checks

The service provides detailed health information:

```json
{
  "status": "healthy",
  "service": "{{ project.name }}",
  "version": "1.0.0",
  "checks": {
    "database": "healthy",
    "external_apis": "healthy",
    "task_queue": {
      "status": "healthy",
      "pending_tasks": 5,
      "active_workers": 3
    }
  }
}
```

### Metrics

Prometheus-compatible metrics are available at `/metrics`:

- Request rate and latency
- Error rates
- Database connection pool status
- Background task queue metrics
- Custom business metrics

### Logging

Structured logging with correlation IDs:

```python
app.logger.info("Processing request", extra={
    "request_id": "req-123",
    "user_id": "user-456",
    "operation": "create_resource"
})
```

## 🧪 Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=.

# Run integration tests
pytest tests/integration/

# Run performance tests
pytest tests/performance/ -v
```

### Test Examples

```python
# Unit test example
async def test_create_resource():
    resource_data = {"name": "Test", "description": "Test resource"}
    resource = await business_logic.create_resource(resource_data)
    assert resource.name == "Test"

# Integration test example
async def test_api_create_resource(client):
    response = await client.post("/api/v1/resources", json={
        "name": "Test Resource",
        "description": "Test"
    })
    assert response.status_code == 201
    assert response.json()["name"] == "Test Resource"
```

## 🔄 CI/CD Pipeline

### GitHub Actions Example

```yaml
name: CI/CD Pipeline

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Set up Python
        uses: actions/setup-python@v2
        with:
          python-version: 3.11
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        run: pytest --cov=.
      
  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - name: Deploy to production
        run: echo "Deploy to production"
```

## 🐳 Docker Deployment

### Dockerfile

```dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
EXPOSE 8000

CMD ["granian", "--interface", "rsgi", "--host", "0.0.0.0", "--port", "8000", "app:app"]
```

### Docker Compose

```yaml
version: '3.8'
services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/myservice
    depends_on:
      - db
      - redis
  
  db:
    image: postgres:15
    environment:
      POSTGRES_DB: myservice
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
  
  redis:
    image: redis:7-alpine
```

## ☸️ Kubernetes Deployment

### Deployment Manifest

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ project.name }}
spec:
  replicas: 3
  selector:
    matchLabels:
      app: {{ project.name }}
  template:
    metadata:
      labels:
        app: {{ project.name }}
    spec:
      containers:
      - name: api
        image: {{ project.name }}:latest
        ports:
        - containerPort: 8000
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: db-secret
              key: url
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 30
          periodSeconds: 10
```

## 🔧 Configuration Management

### Environment-based Configuration

```python
# config/settings.py
import os
from pydantic import BaseSettings

class Settings(BaseSettings):
    service_version: str = "1.0.0"
    environment: str = "development"
    debug: bool = False
    
    # Database
    database_url: str
    
    # Authentication
    secret_key: str
    require_auth: bool = True
    
    # Rate limiting
    rate_limit_requests: int = 100
    rate_limit_window: int = 60
    
    # Features
    enable_sync: bool = True
    enable_notifications: bool = True
    
    class Config:
        env_file = ".env"

settings = Settings()
```

## 📝 Error Handling

### Standard Error Responses

```json
{
  "error": "Validation failed",
  "details": [
    {
      "field": "name",
      "message": "This field is required"
    }
  ],
  "request_id": "req-123",
  "timestamp": "2023-01-01T12:00:00Z"
}
```

### Custom Exception Handling

```python
from gobstopper.http.response import JSONResponse

@app.exception_handler(ValidationError)
async def validation_exception_handler(request, exc):
    return JSONResponse(
        {
            "error": "Validation failed",
            "details": exc.errors()
        },
        status_code=400
    )
```

## 🔐 Security Best Practices

- Input validation on all endpoints
- SQL injection prevention
- XSS protection
- CSRF protection for web endpoints
- Rate limiting to prevent abuse
- Secure webhook signature verification
- Proper error handling (don't leak sensitive info)
- Dependency vulnerability scanning

## 📚 Additional Resources

- [Gobstopper Framework Documentation](https://wopr-framework.readthedocs.io/)
- [API Design Guidelines](docs/api-guidelines.md)
- [Deployment Guide](docs/deployment.md)
- [Troubleshooting Guide](docs/troubleshooting.md)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

## 📝 License

[Your License Here]

## 🙏 Acknowledgments

Built with [Gobstopper Framework](https://github.com/yourusername/wopr)