Skip to Content
DevelopmentBackendOverview

Backend Documentation

Welcome to the Rhesis Backend documentation. This section covers the FastAPI-based backend service that powers the Rhesis platform.

Backend Overview The Rhesis backend is built with FastAPI and provides REST APIs, authentication, business logic, and data management for the entire platform.

Quick Start

Prerequisites

Before working with the backend, ensure you have:

System Requirements - Python 3.8+ with uv  package manager - PostgreSQL database (for production) - Redis (for caching and background tasks) - Environment variables configured

Development Setup

backend-setup.sh
# Navigate to backend directory
cd apps/backend

# Install dependencies
uv sync

# Set up environment
cp ../../.env.example .env
# Edit .env with your configuration

# Run database migrations
uv run alembic upgrade head

# Start development server
./start.sh

Architecture

System Overview

FastAPI Application

Modern, fast web framework for building APIs with automatic documentation.

SQLAlchemy ORM

Database abstraction layer with migration support via Alembic.

Celery Workers

Background task processing for long-running operations.

Authentication

JWT-based authentication with role-based access control.

Multi-tenancy

Organizational isolation and data separation.

API Gateway

RESTful API endpoints with OpenAPI documentation.

Core Components

Application Structure:

backend-structure.txt
apps/backend/
├── src/rhesis/backend/
│   ├── app/
│   │   ├── main.py          # FastAPI application entry point
│   │   ├── api/             # API route definitions
│   │   ├── core/            # Core configuration and settings
│   │   ├── models/          # SQLAlchemy database models
│   │   ├── services/        # Business logic services
│   │   └── utils/           # Utility functions
│   ├── alembic/             # Database migration scripts
│   └── tests/               # Test suite
├── start.sh                 # Development startup script
└── pyproject.toml          # Python dependencies

API Structure

RESTful Endpoints

The backend provides comprehensive REST APIs organized by functionality:

Authentication

User registration, login, and JWT token management.

Organizations

Multi-tenant organization management and isolation.

Projects

Project creation, management, and configuration.

Tests

Test case management and execution tracking.

Test Results

Results storage, analysis, and reporting.

Users

User profile and permission management.

API Documentation

API Features - Automatic Documentation - Generated from code and type hints - Request Validation - Built-in Pydantic validation - Response Serialization - Automatic JSON serialization - Error Handling - Consistent error responses - Rate Limiting - API rate limiting and throttling

Authentication & Security

JWT Authentication

The backend uses JWT (JSON Web Tokens) for stateless authentication:

jwt-token.json
// Example JWT token structure
{
"sub": "user_id",
"org_id": "organization_id",
"permissions": ["read", "write"],
"exp": 1640995200
}

Security Features

JWT Tokens

Stateless authentication with configurable expiration.

Role-Based Access

Granular permissions and role management.

API Rate Limiting

Protection against abuse and DDoS attacks.

CORS Configuration

Cross-origin resource sharing policies.

Input Validation

Comprehensive request validation and sanitization.

Multi-tenancy

Organizations provide data isolation and user management:

organization-access.py
# Organization-based data access
@router.get("/tests/")
async def get_tests(
  current_user: User = Depends(get_current_user),
  db: Session = Depends(get_db)
):
  return get_tests_for_organization(db, current_user.organization_id)

Database Models

Core Entities

The backend uses SQLAlchemy ORM with the following core models:

User Management:

  • User - User accounts and profiles
  • Organization - Multi-tenant organizations
  • Role - User roles and permissions

Testing:

  • Project - Test projects and configurations
  • Test - Individual test cases
  • TestResult - Test execution results
  • TestSet - Collections of related tests

AI Integration:

  • Model - AI model configurations
  • Prompt - Prompt templates and versions
  • Evaluation - AI evaluation results

Background Tasks

Celery Integration

Long-running operations are handled by Celery workers:

celery-task.py
# Example background task
@celery_app.task
def process_test_results(test_id: int):
  """Process and analyze test results asynchronously."""
  # Long-running analysis
  pass

Task Types

Test Execution

Asynchronous test case execution and monitoring.

Result Analysis

AI-powered analysis of test results and insights.

Report Generation

Automated report generation and export.

Data Processing

Batch processing of large datasets.

Email Notifications

Asynchronous email delivery and notifications.

Development Workflow

Local Development

development-commands.sh
# Start development server
cd apps/backend
./start.sh

# Run tests
uv run pytest

# Run linting
uv run ruff check .

# Format code
uv run ruff format .

Environment Configuration

Key environment variables:

.env
# Database
DATABASE_URL=postgresql://user:pass@localhost/rhesis

# Authentication
SECRET_KEY=your-secret-key
JWT_ALGORITHM=HS256

# Redis (for Celery)
REDIS_URL=redis://localhost:6379

# External Services
OPENAI_API_KEY=your-openai-key

Deployment

Production Deployment

The backend supports multiple deployment strategies:

Docker Deployment

Containerized deployment with Docker and Docker Compose.

Kubernetes

Scalable deployment on Kubernetes clusters.

Cloud Platforms

Deployment on AWS, GCP, or Azure cloud platforms.

Self-hosted

Traditional server deployment with nginx and gunicorn.

Performance Considerations

Performance Tips - Database Indexing - Optimize query performance - Caching - Redis caching for frequently accessed data - Connection Pooling - Database connection management - Load Balancing - Distribute traffic across multiple instances - Monitoring - Comprehensive logging and metrics

Testing

Test Suite

The backend includes comprehensive testing:

testing-commands.sh
# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=rhesis.backend

# Run specific test categories
uv run pytest tests/api/
uv run pytest tests/services/

Test Categories

Unit Tests

Individual function and class testing.

Integration Tests

API endpoint and database integration testing.

Authentication Tests

JWT and permission testing.

Performance Tests

Load testing and performance validation.

Monitoring & Observability

Health Checks

# Health check endpoint GET /health # Response { "status": "healthy", "database": "connected", "redis": "connected", "timestamp": "2024-01-01T00:00:00Z" }

Logging

Structured logging with configurable levels:

import logging logger = logging.getLogger(__name__) logger.info("User authenticated", extra={"user_id": user.id})

Next Steps - Explore the API Reference for detailed endpoint documentation - Check out Authentication Guide for security implementation - Review Deployment Guide for production setup - Learn about Background Tasks for async processing