Skip to content

KerrasDev/Contact-Management-System-FastAPI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“‡ Contact Management System

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.


๐Ÿง  Overview

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.


โœจ Key Features

Core Functionality

  • 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

Developer Experience

  • 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

๐Ÿ—๏ธ System Architecture

Layered Design

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

Data Flow

API Client / CLI User
        โ†“
   API / UI Layer
        โ†“
   Service Layer (business rules, fuzzy search, validation)
        โ†“
   Database Layer (CRUD operations, SQL queries)
        โ†“
   SQLite Database (persistent storage)

๐Ÿงฑ Project Structure

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

โš™๏ธ Installation Guide

Prerequisites

  • Python 3.8 or higher
  • pip and venv

Step 1: Clone the Repository

git clone <your-repository-url>
cd contact_management_system

Step 2: Create Virtual Environment

Windows:

python -m venv venv
.\venv\Scripts\activate

macOS/Linux:

python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

๐Ÿ”ง Requirements

requirements.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 Python

๐ŸŽฏ How to Use

Running the REST API

Start the FastAPI server:

uvicorn main:app --reload

The 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

Using the Command-Line Interface

Start the CLI:

python ui/cli.py

You'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): 

๐Ÿ“ก API Documentation

Base URL

http://127.0.0.1:8000

Endpoints

POST /contacts/ - Create Contact

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"
}

GET /contacts/ - List Contacts

Query Parameters:

  • skip (int, default: 0): Number of records to skip
  • limit (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"
  }
]

GET /contacts/search/ - Search Contacts

Query Parameters:

  • query (str, required): Search term
  • fuzzy (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
  }
]

GET /contacts/{contact_id} - Get Contact by ID

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"
}

PUT /contacts/{contact_id} - Update Contact

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"
}

DELETE /contacts/{contact_id} - Delete Contact

Response (204): No content

Response (404):

{
  "detail": "Contact not found"
}

๐Ÿ’ก Usage Examples

cURL Examples

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"

Python Requests Example

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']}")

๐ŸŽจ CLI Features

The Command-Line Interface provides a rich, interactive experience:

Key Features

  • 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

Example CLI Session

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚   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)

๐Ÿ—„๏ธ Database Schema

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);

โš™๏ธ Configuration

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"

๐Ÿงช Testing

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

Test Coverage

  • Model Layer: Validation rules, data structure
  • Database Layer: CRUD operations, search queries
  • Service Layer: Business logic, fuzzy search
  • API Layer: Endpoints, error handling, pagination

๐Ÿ” Security Considerations

  • 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

Production Recommendations

  1. Add Authentication: Implement JWT or OAuth2
  2. Use HTTPS: Deploy behind nginx with SSL
  3. Rate Limiting: Prevent API abuse
  4. Environment Variables: Store sensitive config externally
  5. Database Backups: Schedule regular backups
  6. Monitoring: Implement logging and alerting

๐Ÿž Troubleshooting

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.


๐Ÿš€ Deployment

Docker Deployment

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

๐ŸŽฏ Roadmap

  • 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

๐Ÿค Contributing

Contributions welcome! Please follow these guidelines:

  1. Code Style: Follow PEP 8, use type hints
  2. Testing: Add tests for new features
  3. Documentation: Update README and docstrings
  4. Architecture: Maintain layer separation
  5. Commits: Use clear, descriptive commit messages

๐Ÿ“š Additional Resources


๐Ÿ“„ License

This project is open source under the MIT License.


๐Ÿ‘ค Author

Contact Management System v2.0

For issues, questions, or contributions, please open an issue on GitHub.


Built with โค๏ธ using Python, FastAPI, and Rich

About

Contact Management System FastAPI

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages