Customer relationships are the foundation of every successful small business. Whether a company sells products, provides professional services, or operates an online store, maintaining strong relationships with customers is essential for long-term growth.
However, many small businesses still manage their customer information using spreadsheets, notebooks, and scattered email conversations. Although these methods may work initially, they become increasingly difficult to maintain as the business grows.
Important customer details can get lost, sales opportunities may be overlooked, and following up with potential customers can become a time-consuming task.
A Customer Relationship Management (CRM) system provides a practical solution to these challenges. It allows businesses to organize customer information, track sales opportunities, manage interactions, and improve communication from a single application.
The good news is that building a simple CRM does not require a large development team or an expensive enterprise-level infrastructure. With modern web technologies such as React, Python, and PostgreSQL, developers can create a lightweight CRM that addresses the everyday needs of small businesses.
In this article, we will explore how to build a simple CRM from scratch, including its architecture, database design, backend API, frontend interface, authentication, and deployment.
1. Understanding the Requirements
Before writing any code, it is important to understand what a small business actually needs from a CRM.
A common mistake is attempting to build a complete enterprise-level platform with dozens of features. This increases development time and makes the application unnecessarily complicated.
Instead, the first version should focus on solving a few important problems.
Core features
A simple CRM should include the following functionality:
- Customer management: Store customer names, email addresses, phone numbers, and company information.
- Contact management: Maintain communication details and relevant customer information.
- Lead tracking: Record potential customers and monitor their progress through the sales process.
- Sales pipeline: Organize opportunities into stages such as New, Contacted, Qualified, and Converted.
- Task management: Create reminders for follow-up calls, meetings, and emails.
- Activity history: Maintain a record of important customer interactions.
- Search and filtering: Find customers quickly using names, email addresses, or lead status.
- Dashboard: Display important business metrics and upcoming activities.
These features provide enough functionality for many small businesses without introducing unnecessary complexity.
Defining the user roles
A basic CRM can support two types of users.
An administrator can manage users, customers, and overall business settings.
A sales representative can manage assigned customers, update lead statuses, and record customer interactions.
For a smaller business, these roles may initially share many permissions. However, defining them early makes the application easier to extend later.
2. Choosing the Technology Stack
The technology stack should be reliable, affordable, and easy to maintain.
For this project, we will use React for the frontend, Python with FastAPI for the backend, and PostgreSQL for data storage.
Frontend: React
React allows developers to build interactive user interfaces using reusable components.
A CRM contains several repeated interface elements, including customer tables, search fields, navigation menus, forms, and dashboard cards.
React makes it possible to create these elements once and reuse them throughout the application.
Backend: Python and FastAPI
FastAPI is a Python framework for building APIs.
It provides request validation, automatic API documentation, and support for asynchronous operations.
Python is also suitable for implementing business logic, generating reports, and integrating external services.
Database: PostgreSQL
PostgreSQL is a relational database that works well with structured business information.
A CRM naturally contains relationships between users, customers, leads, tasks, and activities.
PostgreSQL allows developers to represent these relationships using tables, primary keys, and foreign keys.
Supporting technologies
The project can also use:
- SQLAlchemy for database interactions.
- Alembic for database migrations.
- Pydantic for data validation.
- React Router for frontend navigation.
- A CSS framework or custom CSS for responsive styling.
- Docker for consistent development and deployment environments.
The goal is not to use every available technology. It is to select tools that solve the application's actual requirements.
3. Designing the Application Architecture
A simple CRM can follow a three-layer architecture.
The frontend handles user interaction and displays customer information.
The backend processes requests, validates data, enforces permissions, and applies business rules.
The database stores customer records and maintains relationships between different entities.
The general request flow looks like this:
- A sales representative opens the CRM dashboard.
- React requests customer information from the backend.
- FastAPI validates the request and checks the user's permissions.
- The backend retrieves the required records from PostgreSQL.
- The API returns structured JSON data.
- React displays the information in the interface.
This architecture separates presentation, business logic, and data storage.
As a result, developers can update the frontend without rewriting database logic or modify backend functionality without redesigning the entire application.
4. Designing the Database
Database design is one of the most important parts of building a CRM.
A poorly structured database can lead to duplicated customer information, inconsistent records, and difficult reporting.
A simple CRM can begin with five main tables.
Users table
The users table stores information about employees who can access the CRM.
Important fields include:
- id
- name
- email
- password_hash
- role
- created_at
The password must never be stored as plain text. It should be securely hashed using an established password-hashing algorithm.
Customers table
The customers table contains the main customer information.
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(150) NOT NULL,
email VARCHAR(255),
phone VARCHAR(30),
company VARCHAR(150),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
This table stores basic customer information and provides a stable identifier for each record.
The email field should not automatically be treated as globally unique because a business may have multiple contacts associated with the same email address.
Leads table
A lead represents a potential sales opportunity.
CREATE TABLE leads (
id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
title VARCHAR(200) NOT NULL,
status VARCHAR(30) DEFAULT 'new',
estimated_value NUMERIC(12, 2),
assigned_to INTEGER REFERENCES users(id),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
A lead can be associated with a customer and assigned to a sales representative.
The status field indicates the current position of the opportunity in the sales pipeline.
Tasks table
The tasks table stores activities that require attention.
CREATE TABLE tasks (
id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
assigned_to INTEGER REFERENCES users(id),
title VARCHAR(200) NOT NULL,
due_date TIMESTAMP,
completed BOOLEAN DEFAULT FALSE
);
This table allows employees to schedule follow-up calls, meetings, and other customer-related activities.
Activities table
The activities table maintains a history of customer interactions.
CREATE TABLE activities (
id SERIAL PRIMARY KEY,
customer_id INTEGER REFERENCES customers(id),
user_id INTEGER REFERENCES users(id),
activity_type VARCHAR(50),
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Whenever an employee records an important interaction, the application can create a corresponding activity record.
For a production system, the schema should also include appropriate indexes, tenant or business ownership fields, and carefully defined deletion rules.
5. Building the Backend with FastAPI
The backend is responsible for handling requests and enforcing business rules.
Start by creating a project directory.
simple-crm/
backend/
app/
main.py
database.py
models.py
schemas.py
routes/
customers.py
leads.py
tasks.py
requirements.txt
frontend/
Inside the backend directory, install the required packages.
pip install fastapi uvicorn sqlalchemy \
psycopg[binary] pydantic-settings
The application can then be started using Uvicorn.
uvicorn app.main:app --reload
FastAPI automatically provides interactive API documentation, making it easier to test endpoints during development.
Creating the FastAPI application
The main application file initializes FastAPI and registers the required routes.
from fastapi import FastAPI
from app.routes import customers, leads, tasks
app = FastAPI(title="Simple CRM API")
app.include_router(
customers.router,
prefix="/api/customers",
tags=["Customers"]
)
app.include_router(
leads.router,
prefix="/api/leads",
tags=["Leads"]
)
app.include_router(
tasks.router,
prefix="/api/tasks",
tags=["Tasks"]
)
@app.get("/api/health")
def health_check():
return {"status": "healthy"}
Keeping routes in separate modules makes the application easier to understand and maintain.
Creating customer endpoints
The CRM needs endpoints for creating, retrieving, updating, and deleting customer records.
A typical API structure looks like this:
| Method | Endpoint | Purpose |
| GET | /api/customers | List customers |
| GET | /api/customers/{id} | Retrieve one customer |
| POST | /api/customers | Create a customer |
| PATCH | /api/customers/{id} | Update a customer |
| DELETE | /api/customers/{id} | Delete a customer |
For example, the following endpoint creates a customer record.
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import Customer
from app.schemas import CustomerCreate
router = APIRouter()
@router.post("/")
def create_customer(
data: CustomerCreate,
db: Session = Depends(get_db)
):
customer = Customer(**data.model_dump())
db.add(customer)
db.commit()
db.refresh(customer)
return customer
This endpoint receives validated customer information, creates a database record, and returns the saved customer.
In a production application, the endpoint should also use an authenticated user, apply authorization checks, and return an appropriate response schema.
Data validation prevents incomplete or invalid information from entering the database.
Pydantic schemas can define the fields that users are allowed to submit.
from pydantic import BaseModel, EmailStr
class CustomerCreate(BaseModel):
name: str
email: EmailStr | None = None
phone: str | None = None
company: str | None = None
The application can reject invalid email addresses or missing required fields before attempting to save the record.
Validation should also enforce reasonable field lengths and prevent unexpected input from reaching business logic.
6. Implementing Lead Management
Lead management is one of the most valuable features of a CRM.
A business may receive leads from website forms, social media campaigns, email inquiries, or direct customer conversations.
Without a structured process, sales representatives can easily lose track of potential customers.
A simple CRM can organize leads into the following stages:
- New: A potential customer has entered the system.
- Contacted: The business has contacted the potential customer.
- Qualified: The lead appears suitable for the business.
- Proposal: A quotation or proposal has been shared.
- Converted: The lead has become a customer.
- Lost: The opportunity did not result in a sale.
These stages can be represented using a simple status field.
However, the backend should validate every status transition rather than accepting arbitrary values.
For example, a lead should not be marked as converted unless the required business conditions have been satisfied.
Updating lead status
A dedicated endpoint can update the status of a lead.
from fastapi import HTTPException
@router.patch("/{lead_id}/status")
def update_lead_status(
lead_id: int,
status: str,
db: Session = Depends(get_db)
):
allowed_statuses = {
"new",
"contacted",
"qualified",
"proposal",
"converted",
"lost"
}
if status not in allowed_statuses:
raise HTTPException(
status_code=400,
detail="Invalid lead status"
)
lead = db.get(Lead, lead_id)
if not lead:
raise HTTPException(
status_code=404,
detail="Lead not found"
)
lead.status = status
db.commit()
return {"message": "Lead status updated"}
This example demonstrates the basic logic. A production version should use a validated request model, enforce permitted transitions, and record the change in the activity history.
7. Building the Frontend with React
The frontend provides the interface through which employees interact with the CRM.
A simple CRM can contain four main pages:
- Dashboard
- Customers
- Leads
- Tasks
A navigation menu allows employees to move between these pages.
The dashboard displays important metrics, while the customer and lead pages provide tools for managing business information.
Creating reusable components
React components make the interface easier to maintain.
A basic component structure might look like this:
src/
components/
Sidebar.jsx
Header.jsx
CustomerTable.jsx
CustomerForm.jsx
LeadCard.jsx
TaskList.jsx
pages/
Dashboard.jsx
Customers.jsx
Leads.jsx
Tasks.jsx
services/
api.js
App.jsx
Each component should have a clear responsibility.
For example, the CustomerTable component displays customer records, while CustomerForm handles customer creation and editing.
Reusable components reduce duplication and make future changes easier.
Fetching customers from the API
The frontend needs to retrieve customer information from the backend.
A simple React component can use the useEffect hook to load data.
import { useEffect, useState } from "react";
function Customers() {
const [customers, setCustomers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadCustomers() {
try {
const response = await fetch(
"/api/customers"
);
if (!response.ok) {
throw new Error("Unable to load customers");
}
const data = await response.json();
setCustomers(data);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
loadCustomers();
}, []);
if (loading) {
return <p>Loading customers...</p>;
}
return (
<div>
<h1>Customers</h1>
{customers.map((customer) => (
<div key={customer.id}>
{customer.name}
</div>
))}
</div>
);
}
export default Customers;
This example demonstrates the basic data-fetching process.
A more complete interface should also display meaningful error messages, support empty states, and provide a way to retry failed requests.
The customer form should allow employees to enter information such as name, email, phone number, and company.
When the form is submitted, React sends a POST request to the backend.
The interface should provide immediate feedback after successful creation.
For example, the customer list can refresh automatically to display the newly created record.
Form validation should happen on both the frontend and backend. Frontend validation improves usability, while backend validation protects the application's data.
8. Creating a Useful CRM Dashboard
A dashboard gives business owners and sales representatives a quick overview of their current activities.
Instead of displaying every available metric, a simple CRM should focus on information that helps employees make decisions.
Useful dashboard metrics include:
- Total number of customers.
- Number of active leads.
- Number of converted leads.
- Total estimated value of active opportunities.
- Overdue tasks.
- Upcoming follow-up activities.
These metrics can be displayed using small summary cards.
For example, a dashboard might show that the business has 120 customers, 18 active leads, and 7 overdue tasks.
The dashboard can also include a list of recent customer interactions and upcoming appointments.
Calculating sales metrics
The backend can calculate dashboard metrics using database queries.
For example, the total number of active leads can be calculated by counting leads that have not been converted or marked as lost.
The estimated pipeline value can be calculated by summing the estimated values of active opportunities.
These calculations should be performed on the backend rather than downloading every lead record to the frontend.
This approach reduces unnecessary data transfer and makes the application more efficient as the number of customers increases.
9. Adding Search and Filtering
As the customer database grows, employees need an efficient way to find specific records.
A search feature can allow users to search by customer name, email address, or company.
The backend can expose a query parameter.
@router.get("/")
def list_customers(
search: str | None = None,
db: Session = Depends(get_db)
):
query = db.query(Customer)
if search:
query = query.filter(
Customer.name.ilike(f"%{search}%")
)
return query.limit(50).all()
This endpoint demonstrates a simple search implementation.
For production use, developers should consider pagination, database indexes, and search across additional fields.
The query should also use a safe parameterized database operation. User input must never be inserted directly into raw SQL strings.
Filtering can be extended to include lead status, assigned employee, company, and creation date.
These features allow sales representatives to focus on relevant customer records instead of manually reviewing the entire database.
10. Implementing Task Management
Following up with customers is essential for maintaining business relationships.
A CRM should allow employees to create tasks related to specific customers or leads.
For example, a sales representative might create a task to call a potential customer tomorrow afternoon.
The task should contain a title, due date, assigned employee, and completion status.
The task list can display overdue activities separately from upcoming activities.
A simple task management interface should support:
- Creating new tasks.
- Editing task details.
- Marking tasks as completed.
- Filtering tasks by due date.
- Viewing tasks assigned to the current user.
The backend can also provide an endpoint for retrieving overdue tasks.
from datetime import datetime
@router.get("/overdue")
def get_overdue_tasks(
db: Session = Depends(get_db)
):
return db.query(Task).filter(
Task.due_date < datetime.utcnow(),
Task.completed == False
).all()
This is a simplified example. In production, the application should use timezone-aware timestamps and the current user's permitted data scope.
Task reminders can be introduced later through email or notification integrations.
11. Implementing Authentication and Security
A CRM stores valuable business information, so security must be considered from the beginning.
The application should require users to authenticate before accessing customer records.
A common approach is to use secure session-based authentication or short-lived access tokens with an appropriate refresh mechanism.
For a small business application, secure server-managed sessions can be a practical choice.
The backend should verify the user's identity and permissions on every protected request.
Essential security practices
Important security measures include:
- Hash passwords using a suitable password-hashing algorithm.
- Use HTTPS in production.
- Validate all incoming data.
- Protect against unauthorized access.
- Store secrets in environment variables.
- Apply rate limits to sensitive endpoints.
- Avoid exposing internal error details.
- Keep dependencies updated.
- Use secure cookie settings when using session authentication.
Authorization is particularly important when multiple businesses share the same application.
Every customer, lead, task, and activity must be associated with the correct business account.
The backend should enforce this ownership relationship on every query and update.
Simply hiding another business's records in the frontend is not sufficient.
12. Testing the CRM
Testing helps developers identify problems before the application is used by real customers.
The testing process should cover both individual functions and complete user workflows.
Backend testing
Backend tests can verify that:
- A customer can be created successfully.
- Invalid customer information is rejected.
- A nonexistent customer returns a 404 response.
- Lead statuses are validated correctly.
- Unauthorized users cannot access protected records.
- Users cannot retrieve records belonging to another business.
FastAPI's testing utilities and Python testing frameworks can be used to automate these checks.
Frontend testing
Frontend tests should verify that forms display validation messages, customer records render correctly, and users receive feedback after successful operations.
Developers should also test the application on different screen sizes.
Small business employees may access their CRM using laptops, tablets, or mobile devices.
A responsive layout ensures that essential functionality remains accessible across different devices.
13. Deploying the Application
Once the CRM has been tested locally, it can be deployed to a production environment.
A simple deployment architecture consists of a frontend application, a Python API server, and a managed PostgreSQL database.
The frontend can be served through a static hosting platform or a web server.
The backend can run on a cloud application service or a virtual private server.
The database should use a managed service or another properly secured production database environment.
Deployment checklist
Before releasing the application, developers should:
- Configure production environment variables.
- Set up HTTPS.
- Apply database migrations.
- Configure database backups.
- Disable development-only debugging features.
- Configure allowed frontend origins.
- Set up application logging.
- Verify authentication and authorization.
- Test the production environment.
- Establish a backup and recovery procedure.
A production CRM should also have a documented process for restoring customer records if something goes wrong.
A simple CRM does not need a complex infrastructure from the beginning.
However, developers should avoid design decisions that make future growth unnecessarily difficult.
Database indexes can improve the performance of frequently used search and filtering operations.
Pagination prevents the frontend from loading thousands of customer records at once.
Database connection pooling helps the backend manage connections efficiently.
Caching can be introduced for frequently requested dashboard metrics when database queries become expensive.
For more advanced reporting, developers can use carefully designed aggregate queries rather than retrieving every record.
The most important principle is to measure performance before introducing unnecessary optimization.
15. Future Features and Integrations
Once the core CRM is stable, developers can introduce additional functionality based on actual business requirements.
Potential improvements include:
- Email integration for recording customer conversations.
- Automated follow-up reminders.
- CSV import and export.
- Lead capture from website contact forms.
- Sales performance reports.
- Customer segmentation.
- Integration with marketing platforms.
- Activity notifications.
- Mobile-friendly customer management.
- AI-assisted customer communication summaries.
For example, a small digital marketing agency could integrate its CRM with lead-generation campaigns.
Incoming leads could be added automatically, assigned to sales representatives, and tracked through the sales pipeline.
This would reduce manual data entry and improve the agency's ability to monitor its sales opportunities.
However, integrations should be added gradually. The CRM should first provide reliable customer management and accurate business records.
Conclusion
Building a simple CRM for small businesses is an excellent full-stack development project because it combines practical business requirements with important software engineering concepts.
React provides a flexible interface for managing customers, leads, and tasks. Python with FastAPI handles business logic and API requests, while PostgreSQL stores the application's structured information.
By starting with a small set of essential features, developers can build a CRM that is affordable, maintainable, and useful for everyday business operations.
The most important part of the process is understanding the needs of the business before writing code.
A well-designed CRM does not need hundreds of features to provide value. It needs to help employees organize customer information, maintain meaningful relationships, and follow up on sales opportunities consistently.
With a solid architecture, secure data handling, and a clear development plan, a simple CRM can become a valuable tool for small businesses while providing a strong foundation for future improvements.