A comprehensive, production-ready contact management system built in Python, featuring both a FastAPI RESTful API and an interactive Command-Line Interface. Designed with clean architecture and separation of concerns to ensure maintainability, scalability, and enterprise-grade quality.
This project provides a complete solution for managing personal or business contacts through multiple interfaces:
- RESTful API - High-performance FastAPI server with automatic documentation
- CLI Interface - Rich-powered terminal UI with interactive menus and tables
- Dual Search Modes - Standard SQL search and intelligent fuzzy matching
- Layered Architecture - Clean separation between API/UI, business logic, and data layers
The system supports full CRUD operations with robust validation, persistent SQLite storage, and comprehensive test coverage.
- Dual Interface Support โ FastAPI REST API + Rich CLI
- Complete CRUD Operations โ Create, Read, Update, Delete with validation
- Smart Search โ SQL-based search and fuzzy string matching with relevance scoring
- Pagination โ Efficiently browse large contact lists
- Data Validation โ Pydantic models with custom validation rules
- Persistent Storage โ SQLite database with optimized indexes
- Clean Architecture โ Layered design with clear separation of concerns
- Type Safety โ Full type hints throughout the codebase
- Comprehensive Testing โ High test coverage with pytest
- API Documentation โ Auto-generated interactive docs with FastAPI
- Logging System โ Configurable logging for debugging and monitoring
- Configuration Management โ Centralized settings with environment variable support
| Layer | Location | Responsibility |
|---|---|---|
| Presentation | api/, ui/ |
FastAPI endpoints and CLI interface |
| Business Logic | services/ |
Contact operations, validation, search |
| Data Access | database/ |
Repository pattern, database operations |
| Data Model | models/ |
Contact structure with validation |
| Configuration | config/ |
Application settings and constants |
| Utilities | utils/ |
Logging and shared helpers |
API Client / CLI User
โ
API / UI Layer
โ
Service Layer (business rules, fuzzy search, validation)
โ
Database Layer (CRUD operations, SQL queries)
โ
SQLite Database (persistent storage)
contact_management_system/
โ
โโโ api/
โ โโโ api_contact.py # FastAPI routes and endpoints
โ
โโโ ui/
โ โโโ cli.py # Rich-powered CLI interface
โ
โโโ config/
โ โโโ __init__.py
โ โโโ settings.py # Configuration constants
โ
โโโ models/
โ โโโ __init__.py
โ โโโ contact.py # Contact dataclass with Pydantic validation
โ
โโโ database/
โ โโโ __init__.py
โ โโโ db_manager.py # Repository pattern implementation
โ
โโโ services/
โ โโโ __init__.py
โ โโโ contact_service.py # Business logic layer
โ
โโโ utils/
โ โโโ __init__.py
โ โโโ logger.py # Logging configuration
โ
โโโ tests/
โ โโโ test_models.py # Model validation tests
โ โโโ test_database.py # Database operation tests
โ โโโ test_services.py # Business logic tests
โ โโโ test_api.py # API endpoint tests
โ
โโโ main.py # FastAPI application entry point
โโโ requirements.txt # Python dependencies
โโโ README.md # Project documentation
- Python 3.8 or higher
- pip and venv
git clone <your-repository-url>
cd contact_management_systemWindows:
python -m venv venv
.\venv\Scripts\activatemacOS/Linux:
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtrequirements.txt
# Web Framework
fastapi==0.104.1
uvicorn[standard]==0.24.0
# Data Validation
pydantic==2.4.2
pydantic-settings==2.0.3
# CLI Interface
rich==13.7.0
# Fuzzy Search
thefuzz==0.20.0
python-Levenshtein==0.23.0
# Testing
pytest==7.4.3
pytest-mock==3.12.0
# Code Quality
flake8==6.1.0
autopep8==2.0.4
# Note: SQLite3 comes pre-installed with PythonStart the FastAPI server:
uvicorn main:app --reloadThe API will be available at:
- API Base URL:
http://127.0.0.1:8000 - Interactive Docs:
http://127.0.0.1:8000/docs - Alternative Docs:
http://127.0.0.1:8000/redoc
Start the CLI:
python ui/cli.pyYou'll see an interactive menu:
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ CONTACT MANAGEMENT SYSTEM โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
1. Add New Contact
2. View All Contacts
3. Search Contacts
4. Update Contact
5. Delete Contact
6. Exit
Enter your choice (1-6):
http://127.0.0.1:8000
Request Body:
{
"name": "John Doe",
"phone": "+1-555-0123",
"email": "john@example.com",
"address": "123 Main St"
}Response (201):
{
"id": 1,
"name": "John Doe",
"phone": "+1-555-0123",
"email": "john@example.com",
"address": "123 Main St",
"created_at": "2025-11-01T10:30:00",
"updated_at": "2025-11-01T10:30:00"
}Query Parameters:
skip(int, default: 0): Number of records to skiplimit(int, default: 10): Maximum records to return
Response (200):
[
{
"id": 1,
"name": "John Doe",
"phone": "+1-555-0123",
"email": "john@example.com",
"address": "123 Main St",
"created_at": "2025-11-01T10:30:00",
"updated_at": "2025-11-01T10:30:00"
}
]Query Parameters:
query(str, required): Search termfuzzy(bool, default: false): Enable fuzzy matching
Response (200):
[
{
"contact": {
"id": 1,
"name": "John Doe",
"phone": "+1-555-0123",
"email": "john@example.com",
"address": "123 Main St"
},
"score": 95.5
}
]Response (200):
{
"id": 1,
"name": "John Doe",
"phone": "+1-555-0123",
"email": "john@example.com",
"address": "123 Main St",
"created_at": "2025-11-01T10:30:00",
"updated_at": "2025-11-01T10:30:00"
}Response (404):
{
"detail": "Contact not found"
}Request Body: (all fields optional, at least one required)
{
"name": "Jane Doe",
"email": "jane.doe@example.com"
}Response (200):
{
"id": 1,
"name": "Jane Doe",
"phone": "+1-555-0123",
"email": "jane.doe@example.com",
"address": "123 Main St",
"updated_at": "2025-11-01T11:00:00"
}Response (204): No content
Response (404):
{
"detail": "Contact not found"
}Create Contact:
curl -X POST "http://127.0.0.1:8000/contacts/" \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"phone": "555-123-4567",
"email": "john.doe@example.com",
"address": "123 Main St"
}'Search with Fuzzy Matching:
curl "http://127.0.0.1:8000/contacts/search/?query=john&fuzzy=true"Update Contact:
curl -X PUT "http://127.0.0.1:8000/contacts/1" \
-H "Content-Type: application/json" \
-d '{"phone": "555-999-8888"}'Delete Contact:
curl -X DELETE "http://127.0.0.1:8000/contacts/1"import requests
BASE_URL = "http://127.0.0.1:8000"
# Create contact
response = requests.post(
f"{BASE_URL}/contacts/",
json={
"name": "John Doe",
"email": "john@example.com",
"phone": "555-0123"
}
)
contact = response.json()
print(f"Created: {contact['name']} (ID: {contact['id']})")
# Search with fuzzy matching
response = requests.get(
f"{BASE_URL}/contacts/search/",
params={"query": "jon", "fuzzy": True}
)
results = response.json()
for result in results:
print(f"{result['contact']['name']} - Score: {result['score']}")
# Update contact
response = requests.put(
f"{BASE_URL}/contacts/{contact['id']}",
json={"phone": "555-9999"}
)
updated = response.json()
print(f"Updated: {updated['phone']}")The Command-Line Interface provides a rich, interactive experience:
- Menu-Driven Navigation - Clear, numbered options for all operations
- Beautiful Tables - Rich-formatted tables for contact listings
- Interactive Forms - Step-by-step prompts for data entry
- Smart Defaults - Current values shown when updating
- Safe Deletions - Confirmation prompts for destructive actions
- Fuzzy Search - Toggle between standard and fuzzy search modes
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ CONTACT MANAGEMENT SYSTEM โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
1. Add New Contact
2. View All Contacts
3. Search Contacts
4. Update Contact
5. Delete Contact
6. Exit
Enter your choice (1-6): 1
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ Add New Contact โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Enter name: John Doe
Enter phone: 555-0123
Enter email: john@example.com
Enter address: 123 Main St
โ Contact created successfully (ID: 1)
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT,
email TEXT,
address TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Performance indexes
CREATE INDEX idx_contacts_name ON contacts(name);
CREATE INDEX idx_contacts_phone ON contacts(phone);
CREATE INDEX idx_contacts_email ON contacts(email);All settings are centralized in config/settings.py:
class Config:
# Database
DB_NAME = "contacts.db"
# Pagination
PAGE_SIZE = 10
DEFAULT_SKIP = 0
DEFAULT_LIMIT = 10
# Validation
MAX_NAME_LENGTH = 50
MAX_PHONE_LENGTH = 20
MAX_EMAIL_LENGTH = 100
MAX_ADDRESS_LENGTH = 200
PHONE_PATTERN = r'^[\d\s\-\+\(\)]+$'
EMAIL_PATTERN = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Fuzzy Search
FUZZY_SEARCH_THRESHOLD = 60
FUZZY_SEARCH_WEIGHTS = {
'name': 10,
'phone': 5,
'email': 8,
'address': 3
}
# Logging
LOG_LEVEL = "INFO"
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
LOG_FILE = "contact_system.log"Run the comprehensive test suite:
# Run all tests
pytest -v
# Run with coverage report
pytest --cov=. --cov-report=html
# Run specific test file
pytest tests/test_api.py -v
# Run specific test
pytest tests/test_services.py::test_create_contact -v- Model Layer: Validation rules, data structure
- Database Layer: CRUD operations, search queries
- Service Layer: Business logic, fuzzy search
- API Layer: Endpoints, error handling, pagination
- Input Validation: All inputs validated via Pydantic models
- SQL Injection: Protected via parameterized queries
- Email Validation: Regex-based format checking
- Phone Validation: Pattern-based format verification
- Error Handling: Graceful error responses without exposing internals
- Add Authentication: Implement JWT or OAuth2
- Use HTTPS: Deploy behind nginx with SSL
- Rate Limiting: Prevent API abuse
- Environment Variables: Store sensitive config externally
- Database Backups: Schedule regular backups
- Monitoring: Implement logging and alerting
| Issue | Solution |
|---|---|
| Port already in use | Change port: uvicorn main:app --port 8001 |
| Database locked | Close other connections, check file permissions |
| Import errors | Ensure virtual environment is activated |
| Validation errors | Check input formats against patterns in config |
| Dependencies not found | Run pip install -r requirements.txt |
| Tests failing | Ensure test database is clean: delete test_contacts.db |
Check contact_system.log for detailed error messages.
Create Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Build and run:
docker build -t contact-management .
docker run -p 8000:8000 contact-management- GraphQL API support
- Web UI (React/Vue frontend)
- Contact groups/tags
- Export/Import (CSV, JSON, vCard)
- PostgreSQL/MySQL support
- Contact photo attachments
- Email integration
- Calendar integration
- Bulk operations
- Advanced search filters
Contributions welcome! Please follow these guidelines:
- Code Style: Follow PEP 8, use type hints
- Testing: Add tests for new features
- Documentation: Update README and docstrings
- Architecture: Maintain layer separation
- Commits: Use clear, descriptive commit messages
- FastAPI Documentation: https://fastapi.tiangolo.com
- Rich Library: https://rich.readthedocs.io
- Pydantic: https://docs.pydantic.dev
- Pytest: https://docs.pytest.org
This project is open source under the MIT License.
Contact Management System v2.0
For issues, questions, or contributions, please open an issue on GitHub.
Built with โค๏ธ using Python, FastAPI, and Rich