Files
api7-demo/web/README.md
d.viti 1b31601543
All checks were successful
Helm Chart Build / lint-only (push) Has been skipped
Helm Chart Build / build-helm (push) Successful in 8s
Build and Deploy / build-api (push) Successful in 46s
Build and Deploy / build-web (push) Successful in 1m8s
Rewrite and expand all documentation for API7EE demo platform
2025-10-07 19:09:40 +02:00

786 lines
15 KiB
Markdown

# Web Application - FastAPI Frontend with Documentation
A modern web frontend built with FastAPI featuring an interactive dashboard, embedded MkDocs documentation, and API proxy functionality for seamless integration with the backend API service.
## 📋 Overview
This web application serves as the frontend for the API7 Enterprise Edition demo platform, providing:
- **Interactive Dashboard**: Modern UI with real-time statistics
- **Embedded Documentation**: Complete MkDocs documentation site at `/docs`
- **API Proxy**: Seamless proxying of requests to the backend API
- **LLM Chat Interface**: Interactive chat with AI videogame expert
- **Health Monitoring**: Health check endpoints
- **Static Assets**: Custom CSS and JavaScript for enhanced UX
## ✨ Features
### Web Pages
- **Home Page** (`/`): Dashboard with feature overview and statistics
- **Items Page** (`/items`): Browse and manage items
- **Users Page** (`/users`): View and manage users
- **LLM Chat** (`/llm`): Interactive AI chat interface
- **Documentation** (`/docs`): Full project documentation (MkDocs)
### API Proxy Endpoints
The web application proxies the following API endpoints:
- `GET /api/items` → Backend `/items`
- `GET /api/items/{item_id}` → Backend `/items/{item_id}`
- `GET /api/users` → Backend `/users`
- `GET /api/users/{user_id}` → Backend `/users/{user_id}`
- `POST /api/llm/chat` → Backend `/llm/chat`
- `GET /api/llm/models` → Backend `/llm/models`
- `GET /api/llm/health` → Backend `/llm/health`
- `GET /api/config` → Returns frontend configuration
### Documentation Site
The embedded MkDocs documentation includes:
- **Getting Started**: Quick setup guide
- **Architecture**: System architecture and component details
- **Kubernetes Resources**: Complete resource reference
- **API7 Configuration**: Gateway setup and configuration
- **CI/CD Pipeline**: Automation and deployment workflows
- **Troubleshooting**: Common issues and solutions
## 🚀 Quick Start
### Prerequisites
```bash
python >= 3.8
pip
```
### Local Development
#### Install Dependencies
```bash
cd web
pip install -r requirements.txt
```
#### Run the Application
```bash
# Basic run (connects to localhost:8001 by default)
python main.py
# With custom API backend URL
export API_BASE_URL="http://localhost:8001"
python main.py
# Or use uvicorn directly
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
#### Access the Application
- **Home**: http://localhost:8000
- **Items**: http://localhost:8000/items
- **Users**: http://localhost:8000/users
- **LLM Chat**: http://localhost:8000/llm
- **Documentation**: http://localhost:8000/docs
- **Health Check**: http://localhost:8000/health
### Docker
#### Build Image
```bash
docker build -t web-app .
```
The Dockerfile:
1. Installs Python dependencies
2. Copies application code, templates, static assets, and docs
3. Builds static documentation with MkDocs
4. Serves both the app and documentation
#### Run Container
```bash
# Basic run
docker run -p 8000:8000 web-app
# With custom API backend URL
docker run -p 8000:8000 \
-e API_BASE_URL="http://api-backend:8001" \
web-app
# Run with host network (for local testing)
docker run --network host \
-e API_BASE_URL="http://localhost:8001" \
web-app
```
## 🔧 Configuration
### Environment Variables
| Variable | Description | Default | Required |
| -------------- | --------------- | ----------------------- | -------- |
| `API_BASE_URL` | Backend API URL | `http://localhost:8001` | No |
### Example Configuration
**Development**:
```bash
export API_BASE_URL="http://localhost:8001"
python main.py
```
**Docker**:
```bash
docker run -p 8000:8000 \
-e API_BASE_URL="http://api-service:8001" \
web-app
```
**Kubernetes**:
```yaml
env:
- name: API_BASE_URL
value: "http://nginx-service.api7ee.svc.cluster.local:8080"
```
## 📄 Pages and Routes
### HTML Pages
#### `GET /`
Home dashboard with feature cards and statistics.
**Features**:
- Feature cards (Items, Users, LLM, API Docs)
- Real-time statistics (item count, user count)
- Feature highlights
- Links to all sections
#### `GET /items`
Items management page.
**Features**:
- Display all items from API
- Real-time data fetching
- Interactive UI
#### `GET /users`
Users management page.
**Features**:
- Display all users from API
- User information cards
- Real-time data updates
#### `GET /llm`
LLM chat interface.
**Features**:
- Interactive chat with AI
- Markdown rendering for responses
- Token usage display
- Rate limit indicator (100 tokens/60s)
- Model selection (videogame-expert)
- Real-time status updates
### API Proxy Routes
#### `GET /api/items`
Proxy to backend API items endpoint.
**Backend**: `GET {API_BASE_URL}/items`
#### `GET /api/items/{item_id}`
Proxy to backend API specific item endpoint.
**Backend**: `GET {API_BASE_URL}/items/{item_id}`
#### `GET /api/users`
Proxy to backend API users endpoint.
**Backend**: `GET {API_BASE_URL}/users`
#### `GET /api/users/{user_id}`
Proxy to backend API specific user endpoint.
**Backend**: `GET {API_BASE_URL}/users/{user_id}`
#### `POST /api/llm/chat`
Proxy to backend LLM chat endpoint.
**Backend**: `POST {API_BASE_URL}/llm/chat`
**Request Body**:
```json
{
"prompt": "What is Zelda?",
"max_tokens": 150,
"temperature": 0.7,
"model": "videogame-expert"
}
```
#### `GET /api/llm/models`
Proxy to backend LLM models endpoint.
**Backend**: `GET {API_BASE_URL}/llm/models`
#### `GET /api/llm/health`
Proxy to backend LLM health check.
**Backend**: `GET {API_BASE_URL}/llm/health`
### Health Check
#### `GET /health`
Web application health check.
**Response**:
```json
{
"status": "healthy",
"service": "web",
"version": "1.0.0",
"api_backend": "http://localhost:8001",
"api_status": "healthy"
}
```
**API Status Values**:
- `healthy`: Backend is responding
- `unhealthy`: Backend returned non-200 status
- `unreachable`: Cannot connect to backend
### Configuration Endpoint
#### `GET /api/config`
Get current frontend configuration.
**Response**:
```json
{
"api_base_url": "http://localhost:8001"
}
```
## 📚 Documentation
### MkDocs Configuration
The application includes a comprehensive documentation site built with MkDocs Material theme.
**Configuration file**: `mkdocs.yml`
**Theme Features**:
- Material Design theme
- Light/Dark mode toggle
- Navigation tabs and sections
- Search functionality
- Syntax highlighting
- Code copy buttons
### Documentation Structure
```
docs/
├── index.md # Documentation home
├── getting-started.md # Quick start guide
├── architecture.md # System architecture
├── kubernetes-resources.md # K8s resources reference
├── api7-configuration.md # API7 Gateway setup
├── cicd-pipeline.md # CI/CD documentation
└── troubleshooting.md # Troubleshooting guide
```
### Building Documentation
#### Serve Locally (Development)
```bash
cd web
mkdocs serve
# Access at http://localhost:8001
```
#### Build Static Site
```bash
mkdocs build -d site
# Output directory: web/site/
```
The Docker build automatically builds the documentation during image creation.
### Updating Documentation
1. Edit markdown files in `docs/` directory
2. Test locally with `mkdocs serve`
3. Commit changes
4. Rebuild Docker image or re-deploy
## 🎨 Templates and Static Assets
### Templates (Jinja2)
Located in `templates/`:
- **base.html**: Base template with common HTML structure
- **index.html**: Home dashboard page
- **items.html**: Items management page
- **users.html**: Users management page
- **llm.html**: LLM chat interface
### Static Assets
Located in `static/`:
- **css/**: Custom stylesheets
- **js/**: JavaScript files
### Template Variables
Templates have access to:
- `request`: Starlette Request object
- Context variables passed from route handlers
## 🧪 Testing
### Manual Testing
```bash
# Test home page
curl http://localhost:8000/
# Test health check
curl http://localhost:8000/health
# Test API proxy
curl http://localhost:8000/api/items
curl http://localhost:8000/api/users
# Test LLM proxy
curl -X POST http://localhost:8000/api/llm/chat \
-H "Content-Type: application/json" \
-d '{
"prompt": "What is Mario?",
"max_tokens": 100
}'
# Test configuration
curl http://localhost:8000/api/config
```
### Browser Testing
1. Navigate to http://localhost:8000
2. Check all navigation links work
3. Verify items and users load
4. Test LLM chat interface
5. Browse documentation at /docs
## 🐳 Docker
### Dockerfile Breakdown
```dockerfile
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application files
COPY main.py .
COPY docs/ ./docs/
COPY static/ ./static/
COPY templates/ ./templates/
COPY mkdocs.yml .
# Build documentation
RUN mkdocs build -d site
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
### Multi-stage Build Benefits
- Dependencies installed during build
- Documentation pre-built as static files
- Smaller runtime container
- Faster startup time
### Build and Push
```bash
# Build
docker build -t git.commandware.com/demos/api7-demo/web:latest .
# Tag
docker tag git.commandware.com/demos/api7-demo/web:latest \
git.commandware.com/demos/api7-demo/web:v1.0.0
# Push
docker push git.commandware.com/demos/api7-demo/web:latest
docker push git.commandware.com/demos/api7-demo/web:v1.0.0
```
## ☸️ Kubernetes Deployment
### Basic Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-service
namespace: api7ee
spec:
replicas: 2
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: git.commandware.com/demos/api7-demo/web:main
ports:
- containerPort: 8000
name: http
env:
- name: API_BASE_URL
value: "http://nginx-service.api7ee.svc.cluster.local:8080"
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
---
apiVersion: v1
kind: Service
metadata:
name: web-service
namespace: api7ee
spec:
type: ClusterIP
ports:
- port: 80
targetPort: 8000
name: http
selector:
app: web
```
### With Helm
See the [Helm chart README](../helm/api7ee-demo-k8s/README.md) for full deployment options.
```bash
helm install api7ee-demo ./helm/api7ee-demo-k8s \
--set web.image.tag=v1.0.0 \
--set web.replicaCount=3 \
--namespace api7ee
```
## 📦 Dependencies
### Python Requirements
```
fastapi==0.104.1
uvicorn[standard]==0.24.0
jinja2==3.1.3
python-multipart==0.0.6
httpx==0.26.0
mkdocs==1.5.3
mkdocs-material==9.5.3
pymdown-extensions==10.7
```
### Install
```bash
pip install -r requirements.txt
```
### Dependency Breakdown
- **fastapi**: Web framework
- **uvicorn**: ASGI server with WebSocket support
- **jinja2**: Template engine for HTML pages
- **python-multipart**: Form data parsing
- **httpx**: Async HTTP client for API proxying
- **mkdocs**: Documentation site generator
- **mkdocs-material**: Material theme for MkDocs
- **pymdown-extensions**: Additional markdown extensions
## 🚀 Production Deployment
### Recommended Configuration
```yaml
web:
replicaCount: 3
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 15
targetCPUUtilizationPercentage: 80
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 500m
memory: 512Mi
env:
- name: API_BASE_URL
value: "http://nginx-service.api7ee.svc.cluster.local:8080"
```
### API7 Gateway Integration
When deployed behind API7 Gateway:
**Routing**:
- Priority 1: `/*` routes to web service (matches all except `/api`)
- Hosts: `api7-demo.commandware.it`
**Plugins**:
- `redirect`: HTTP → HTTPS enforcement
- No rate limiting on web pages (only on API endpoints)
**Service Discovery**:
```yaml
upstream:
name: apache-upstream
nodes:
- host: apache-service.api7ee.svc.cluster.local
port: 80
weight: 100
```
## 🔒 Security
### Best Practices
1. **Non-root User**: Container runs as non-root (UID 1000)
2. **Read-only Filesystem**: Root filesystem is read-only
3. **CORS**: Configured via API7 Gateway
4. **Input Validation**: FastAPI automatic validation
5. **Proxy Security**: Validates API responses before forwarding
### Security Headers
Consider adding these headers via API7 Gateway:
```yaml
plugins:
response-rewrite:
headers:
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: "1; mode=block"
```
## 📊 Monitoring
### Health Checks
The `/health` endpoint provides:
- Web service status
- API backend connectivity
- API backend health status
**Kubernetes Probes**:
```yaml
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
```
### Logging
Monitor application logs:
```bash
# Docker
docker logs -f web-app
# Kubernetes
kubectl logs -n api7ee -l app=web --tail=100 -f
# Specific pod
kubectl logs -n api7ee web-service-xxx-xxx -f
```
## 🐛 Troubleshooting
### Common Issues
**Issue**: Cannot connect to API backend
```bash
# Check API_BASE_URL
curl http://localhost:8000/api/config
# Check backend health
curl http://localhost:8000/health
# Response shows api_status: "unreachable"
# Solution: Verify API_BASE_URL is correct and backend is running
```
**Issue**: Documentation not showing
```bash
# Rebuild documentation
mkdocs build -d site
# Check if site directory exists
ls -la site/
# Rebuild Docker image
docker build -t web-app .
```
**Issue**: Static assets not loading
```bash
# Check static directory exists
ls -la static/
# Verify static mount in Docker
docker run -it web-app ls -la /app/static
# Check browser console for 404 errors
```
**Issue**: Templates not rendering
```bash
# Check templates directory
ls -la templates/
# Verify template files exist
ls templates/*.html
# Check application logs for Jinja2 errors
docker logs web-app
```
### Debug Mode
Run with debug logging:
```python
# In main.py, add:
import logging
logging.basicConfig(level=logging.DEBUG)
# Or with uvicorn:
uvicorn main:app --log-level debug
```
## 📚 Resources
### Documentation
- **FastAPI**: https://fastapi.tiangolo.com/
- **MkDocs**: https://www.mkdocs.org/
- **MkDocs Material**: https://squidfunk.github.io/mkdocs-material/
- **Jinja2**: https://jinja.palletsprojects.com/
- **HTTPX**: https://www.python-httpx.org/
### Related
- [Main README](../README.md)
- [API Application README](../api/README.md)
- [Helm Chart README](../helm/api7ee-demo-k8s/README.md)
## 🎯 Future Enhancements
Potential improvements:
- [ ] User authentication
- [ ] WebSocket support for real-time updates
- [ ] Progressive Web App (PWA) features
- [ ] Advanced caching strategies
- [ ] Internationalization (i18n)
- [ ] Enhanced error pages
---
**Version**: 1.0.0 | **Port**: 8000 | **Framework**: FastAPI 0.104.1 | **Theme**: Material for MkDocs 9.5.3