What's Been Built (Tasks 2 & 9)
Task #2: Backend Development - FastAPI server with WhatsApp webhook integration
Task #9: Database & Caching - PostgreSQL database and Redis cache setup
Jeevo is a healthcare platform that works entirely within WhatsApp, making medical assistance accessible to rural and semi-urban communities in India. This initial phase establishes the backend infrastructure and data layer.
- FastAPI - Modern Python web framework
- Python 3.10+ - Programming language
- Uvicorn - ASGI server
- httpx - Async HTTP client for WhatsApp API
- PostgreSQL 15 - Primary database
- SQLAlchemy 2.0 - ORM with async support
- Redis 7 - Session management and caching
- asyncpg - Async PostgreSQL driver
-
Python 3.10 or higher
- Download: https://www.python.org/downloads/
-
PostgreSQL 15
- Download: https://www.postgresql.org/download/
-
Redis 7
- Windows: https://github.com/microsoftarchive/redis/releases
- Or use Docker:
docker run --name jeevo-redis -p 6379:6379 -d redis:7-alpine
-
Git (optional, for cloning)
- Download: https://git-scm.com/downloads
- RAM: Minimum 4GB (8GB recommended)
- Disk Space: 2GB free space
- OS: Windows 10+, macOS 10.15+, or Linux
# If using Git:
git clone https://github.com/yourusername/jeevo-backend.git
cd jeevo-backend
# Or download and extract the ZIP file# Create virtual environment
python -m venv venv
# Activate it
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activatepip install -r requirements.txtDependencies installed:
fastapi==0.104.1 # Web framework
uvicorn[standard]==0.24.0 # ASGI server
pydantic==2.5.0 # Data validation
python-dotenv==1.0.0 # Environment variables
httpx==0.25.1 # HTTP client
pydantic-settings==2.1.0 # Settings management
sqlalchemy==2.0.23 # Database ORM
asyncpg==0.29.0 # Async PostgreSQL driver
psycopg2-binary==2.9.9 # PostgreSQL adapter
alembic==1.12.1 # Database migrations
redis==5.0.1 # Redis client
aioredis==2.0.1 # Async RedisCreate a file named .env in the project root:
# Create the file
touch .env # On Linux/Mac
# Or manually create .env file on WindowsCopy this into your .env file:
# Server Configuration
APP_NAME=Jeevo Health Platform
HOST=0.0.0.0
PORT=8000
DEBUG=True
# WhatsApp Cloud API Configuration
WHATSAPP_API_URL=https://graph.facebook.com/v18.0
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id_here
WHATSAPP_ACCESS_TOKEN=your_access_token_here
WHATSAPP_VERIFY_TOKEN=your_custom_verify_token_here
# Webhook Configuration
WEBHOOK_VERIFY_TOKEN=jeevo_secure_token_2024
# Database Configuration
DATABASE_URL=postgresql+asyncpg://postgres:your_password@localhost:5432/jeevo_db
DATABASE_ECHO=True
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_DB=0
REDIS_PASSWORD=
REDIS_TTL=3600
# Session Configuration
SESSION_EXPIRE_MINUTES=60Replace these values:
your_password- Your PostgreSQL passwordyour_phone_number_id_here- From Meta (when you set up WhatsApp)your_access_token_here- From Meta (when you set up WhatsApp)
-
Open pgAdmin
- Press Windows Key β Type "pgAdmin" β Open it
-
Connect to Server
- Expand "Servers" β Click "PostgreSQL 15"
- Enter your password when prompted
-
Create Database
- Right-click "Databases" β "Create" β "Database..."
- Database name:
jeevo_db - Owner:
postgres - Click "Save"
-
Verify Creation
- You should see
jeevo_dbin the database list β
- You should see
# Open terminal and connect to PostgreSQL
psql -U postgres
# Enter your password when prompted
# Create the database
CREATE DATABASE jeevo_db;
# Verify it was created
\l
# Exit
\qCreate a file create_db.py:
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
# Update with your password
DB_PASSWORD = "your_password_here"
try:
conn = psycopg2.connect(
host="localhost",
port="5432",
user="postgres",
password=DB_PASSWORD,
database="postgres"
)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor = conn.cursor()
# Check if database exists
cursor.execute("SELECT 1 FROM pg_database WHERE datname='jeevo_db'")
exists = cursor.fetchone()
if not exists:
cursor.execute("CREATE DATABASE jeevo_db")
print("β
Database 'jeevo_db' created successfully!")
else:
print("βΉοΈ Database 'jeevo_db' already exists")
cursor.close()
conn.close()
except Exception as e:
print(f"β Error: {e}")Run it:
python create_db.pyUsing Docker (Recommended):
docker run --name jeevo-redis -p 6379:6379 -d redis:7-alpineOr if installed locally:
redis-serverPostgreSQL usually starts automatically when your computer boots.
To verify it's running:
- Windows: Services β look for "postgresql-x64-15" β should say "Running"
- macOS:
brew services list | grep postgresql - Linux:
sudo systemctl status postgresql
# Make sure you're in the project directory with venv activated
python -m app.mainExpected output:
==================================================
π Starting Jeevo Health Platform
π± WhatsApp Phone Number ID: your_phone_number_id_here
π§ Debug Mode: True
==================================================
π Initializing PostgreSQL database...
β
Database initialized successfully
π΄ Connecting to Redis...
β
Redis connected - Keys: 0
==================================================
β
All services started successfully!
==================================================
INFO: Uvicorn running on http://0.0.0.0:8000
If you see this, everything is working! β
Open your browser and visit:
http://localhost:8000/health
Expected response:
{
"status": "healthy",
"app": "Jeevo Health Platform",
"version": "1.0.0",
"database": "connected",
"redis": {
"connected": true,
"used_memory": "1.2M",
"total_keys": 0,
"uptime_seconds": 123
}
}Visit:
http://localhost:8000/docs
You should see Swagger UI with all available endpoints:
GET /- Root endpointGET /health- Health checkGET /webhook- Webhook verificationPOST /webhook- Receive messages
- Open pgAdmin
- Navigate to: Servers β PostgreSQL 15 β Databases β jeevo_db β Schemas β public β Tables
You should see 6 tables:
- β
users - β
conversations - β
reminders - β
local_risk_levels - β
health_alerts - β
sessions
All tables are empty initially - they'll populate when WhatsApp messages arrive.
- id (Primary Key)
- phone_number (Unique) - WhatsApp number
- name - User's name
- language - Preferred language (enum)
- city, state, pincode - Location data
- latitude, longitude - Coordinates
- voice_enabled - Voice feature flag
- alerts_enabled - Alerts feature flag
- created_at - Registration timestamp
- last_active - Last interaction
- is_active - Account status- id (Primary Key)
- user_id (Foreign Key β users)
- message_id (Unique) - WhatsApp message ID
- message_type - text/audio/image/video/document
- user_message - User's message content
- bot_response - Bot's reply
- media_url - Media file URL
- media_id - WhatsApp media ID
- created_at - Message timestamp
- response_time_ms - Response latency- id (Primary Key)
- user_id (Foreign Key β users)
- reminder_type - immunization/checkup/medication/test/followup
- title - Reminder title
- description - Reminder details
- scheduled_time - When to send
- sent_at - When actually sent
- is_sent - Sent status
- is_completed - Completion status
- is_recurring - Recurring flag
- recurrence_pattern - daily/weekly/monthly
- created_at, updated_at - Timestamps- id (Primary Key)
- pincode - Area code
- city, state - Location
- risk_level - green/yellow/red (enum)
- risk_factors - JSON array of factors
- active_diseases - JSON array of diseases
- pollution_level - Air quality
- weather_alerts - JSON weather data
- last_updated - Data freshness
- data_source - Source API- id (Primary Key)
- alert_type - outbreak/immunization/weather/safety
- title - Alert headline
- message - Alert content
- target_pincodes - JSON array
- target_cities - JSON array
- target_states - JSON array
- audio_url - Voice announcement URL
- is_active - Active status
- priority - 1=low, 2=medium, 3=high
- created_at - Creation time
- expires_at - Expiration time
- sent_count - Delivery counter- id (Primary Key)
- session_id (Unique) - Session identifier
- phone_number - User's number
- context - JSON conversation context
- state - Current conversation state
- created_at - Session start
- last_accessed - Last activity
- expires_at - Session expiration-
languageenum - Supported languages
en(English),hi(Hindi),mr(Marathi)gu(Gujarati),bn(Bengali),ta(Tamil)te(Telugu),kn(Kannada),ml(Malayalam),pa(Punjabi)
-
remindertype - Reminder categories
immunization,checkup,medication,test,followup
-
risklevel - Risk indicators
green(Low),yellow(Medium),red(High)
jeevo-backend/
βββ app/
β βββ __init__.py
β βββ main.py # FastAPI app entry point
β β
β βββ config/
β β βββ __init__.py
β β βββ settings.py # Environment configuration
β β
β βββ database/
β β βββ __init__.py
β β βββ base.py # Database connection
β β βββ models.py # 6 tables + 3 enums
β β βββ repositories.py # Data access layer (5 repositories)
β β
β βββ routes/
β β βββ __init__.py
β β βββ webhook.py # WhatsApp webhook endpoints
β β
β βββ services/
β β βββ __init__.py
β β βββ whatsapp_service.py # WhatsApp API integration
β β βββ cache_service.py # Redis cache operations
β β
β βββ models/
β β βββ __init__.py
β β βββ message.py # Pydantic models
β β
β βββ utils/
β βββ __init__.py
β βββ helpers.py # Utility functions
β
βββ venv/ # Virtual environment
βββ .env # Environment variables
βββ .gitignore # Git ignore rules
βββ requirements.txt # Dependencies
βββ README.md # This file
GET /Response:
{
"app": "Jeevo Health Platform",
"status": "running",
"message": "Jeevo WhatsApp Health Platform API is active"
}GET /healthResponse:
{
"status": "healthy",
"app": "Jeevo Health Platform",
"version": "1.0.0",
"database": "connected",
"redis": {
"connected": true,
"used_memory": "1.2M",
"total_keys": 0,
"uptime_seconds": 123
}
}GET /webhook?hub.mode=subscribe&hub.verify_token=TOKEN&hub.challenge=CHALLENGEResponse: Returns the challenge string (for Meta verification)
POST /webhookRequest: WhatsApp webhook payload (JSON)
Response: {"status": "ok"}
What happens when a message arrives:
- Message is parsed
- User is fetched or created
- Message is marked as read
- Conversation is saved to database
- User context is cached in Redis
- Response is sent back to WhatsApp
1. User sends WhatsApp message
β
2. Meta WhatsApp Cloud API receives it
β
3. POST /webhook is called on your server
β
4. Message is parsed (text/audio/image/etc.)
β
5. User is fetched from PostgreSQL (or created if new)
β
6. Message is marked as read
β
7. Response is generated (currently echo/welcome)
β
8. Conversation is saved to PostgreSQL
β
9. User context is cached in Redis
β
10. Response is sent via WhatsApp API
PostgreSQL:
- Stores users permanently
- Stores all conversation history
- Stores reminders (for future use)
- Stores risk levels (for future use)
- Stores health alerts (for future use)
Redis:
- Caches user sessions (60 min expiry)
- Caches conversation context (30 min expiry)
- Caches risk levels (1 hour expiry)
- Provides fast access to recent data
Backend infrastructure and database layer are fully functional and ready for AI integration.
Made with β€οΈ for rural India's healthcare accessibility