Backend Service Documentation
The Backend Service (also known as the API Gateway) is the central entry point for all client requests in the TFG-Chatbot system. It handles authentication, authorization, session management, and routes requests to the appropriate microservices.
Quick Overview
| Aspect | Details |
|---|---|
| Technology | FastAPI, Python 3.13+ |
| Database | MongoDB |
| Port | 8000 |
| Purpose | API Gateway, Auth, Session Management |
| Container | Docker (Docker Compose) |
Directory Structure
backend/
├── __main__.py # Entry point
├── api.py # FastAPI application setup
├── config.py # Configuration management
├── security.py # JWT, hashing, auth dependencies
├── dependencies.py # FastAPI dependency injection
├── logging_config.py # Logging configuration
├── utils.py # Utility functions
├── Dockerfile # Container definition
├── pyproject.toml # Project metadata & dependencies
├── routers/ # API endpoints
│ ├── auth.py # Authentication endpoints
│ ├── users.py # User profile management
│ ├── subjects.py # Subject CRUD operations
│ ├── chat.py # Chatbot service proxy
│ ├── sessions.py # Session management
│ ├── professor.py # Professor-specific endpoints
│ └── admin.py # Admin tools
├── models/ # Pydantic models
│ ├── admin.py
│ ├── common.py
│ └── professor.py
├── db/ # Database utilities
│ └── mongo.py # MongoDB connection
└── tests/ # Unit & integration tests
Key Features
- JWT-based Authentication: Secure token-based user authentication
- Role-Based Access Control (RBAC): Three roles -
student,professor,admin - API Gateway Pattern: Proxies requests to chatbot and RAG services
- Session Management: Track and manage user chat sessions
- Subject Management: Handle academic subjects and enrollment
- Prometheus Metrics: Built-in monitoring and observability
Documentation Files
- README.md - This file, overview and quick start
- architecture.md - System design, data models, and patterns
- api-endpoints.md - Complete API reference with examples
- authentication.md - Auth flow, JWT, RBAC, security
- configuration.md - Environment variables, settings
- database.md - MongoDB schema, collections, queries
- development.md - Setup, running, testing, debugging
- deployment.md - Docker, production considerations
Quick Start
Prerequisites
- Python 3.13+
- uv (package manager)
- MongoDB instance (or Docker Compose for full stack)
Setup
cd backend
uv sync
Run Locally
# Install dependencies
uv sync
# Run the service
uv run python -m backend
The API will be available at http://localhost:8000
Run Tests
# Run all tests
uv run pytest tests/
# Run specific test file
uv run pytest tests/unit/test_auth.py -v
# Run with coverage
uv run pytest tests/ --cov=backend
Docker
# Build image
docker build -t tfg-backend:latest .
# Run container
docker run -p 8000:8000 --env-file .env tfg-backend:latest
API Documentation
Once running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
Architecture Highlights
Authentication Flow
- User submits credentials (
/auth/login) - Backend validates against MongoDB
- JWT token generated and returned
- Token used in subsequent requests via
Authorization: Bearer <token>
Request Flow
flowchart TD
A[Client Request] --> B[Authentication Middleware]
B --> C{JWT Valid?}
C -->|Yes| D[Authorization Check - RBAC]
C -->|No| E[401 Unauthorized]
D --> F{Has Permission?}
F -->|Yes| G[Route Handler]
F -->|No| H[403 Forbidden]
G --> I{Needs External Service?}
I -->|Yes| J[Proxy to Chatbot/RAG]
I -->|No| K[Process Locally]
J --> L[Response to Client]
K --> L
Service Communication
flowchart LR
Client([Client]) --> Backend[Backend<br/>Port 8000]
Backend --> Chatbot[Chatbot Service<br/>Port 8080]
Backend --> RAG[RAG Service<br/>Port 8081]
Backend --> MongoDB[(MongoDB<br/>Port 27017)]
Key Concepts
User Roles
- STUDENT: Can start chats, take tests, view subjects
- PROFESSOR: Can manage subjects, create tests, view analytics
- ADMIN: Full system access, user management
Sessions
Each chat interaction is tracked as a session:
- Tied to specific user and subject
- Thread ID stored for LangGraph checkpointing
- Conversation history maintained
Subjects
Academic subjects with:
- CRUD operations
- Student enrollment
- Teaching guide (guía docente) integration
Configuration
Environment variables control behavior:
# Database
MONGODB_URI=mongodb://localhost:27017
# JWT
SECRET_KEY=your-secret-key
ALGORITHM=HS256
# Services
CHATBOT_SERVICE_URL=http://chatbot:8080
RAG_SERVICE_URL=http://rag_service:8081
# Logging
LOG_LEVEL=INFO
See configuration.md for complete reference.
Testing
The project uses pytest with:
- Unit tests: Fast, isolated, no external dependencies
- Integration tests: Test service communication
- Markers:
@pytest.mark.unit,@pytest.mark.integration - Fixtures: Common test data (users, tokens, etc.)
Example:
# Run only unit tests
uv run pytest tests/ -m unit -v
Common Tasks
Add a New Endpoint
- Create a router function in
routers/ - Use
@router.get(),@router.post(), etc. - Add Pydantic models in
models/if needed - Write tests in
tests/ - Register router in
api.py
Query MongoDB
from backend.db.mongo import get_db
db = get_db()
users = db["users"].find_one({"email": "user@example.com"})
Generate JWT Token
from backend.security import create_access_token
token = create_access_token(
data={"sub": user_id, "role": user_role}
)
Troubleshooting
Cannot Connect to MongoDB
- Ensure MongoDB is running
- Check
MONGODB_URIin.env - Verify network connectivity in Docker Compose
JWT Token Expired
- Tokens expire after set duration (see config)
- Client must call
/auth/loginto refresh or get new token
Service Not Responding
- Check logs:
docker logs tfg-backend - Verify service URL environment variables
- Ensure other services are running
Performance Considerations
- Database Indexing: Optimize MongoDB queries with proper indexes
- Caching: Consider caching frequently accessed subjects/users
- Rate Limiting: Implement if public API
- Monitoring: Use Prometheus metrics (
/metricsendpoint)
Security Best Practices
- Always use
SECRET_KEYenvironment variable - Validate all user inputs via Pydantic models
- Use
bcryptfor password hashing - Implement rate limiting on auth endpoints
- Keep dependencies updated
Related Services
- Chatbot Service: AI agent for question answering
- RAG Service: Document indexing and retrieval
- Frontend: User interface
Support & Resources
- Project Root: TFG-Chatbot
- Main Documentation: docs/
- ADRs: docs/ADR/
- Architecture Overview: docs/guide/architecture.md