API Reference
Complete reference for CareLog's service layer APIs.
Service Architecture
All services follow a consistent pattern with CRUD operations and additional business logic methods.
DatabaseService
Core service for JSON-based data persistence.
Constructor
DatabaseService(db_path: str = "data/data.json")Parameters:
db_path: Path to JSON database file
Methods
get(key: str) -> Any
Retrieve data by key.
users = db_service.get("users")update(key: str, value: Any) -> None
Update or create data by key.
db_service.update("users", {"user1": {...}})get_user_by_role(role: str) -> List[Dict]
Get all users with specified role.
doctors = db_service.get_user_by_role("doctor")get_name_by_user_id(user_id: str) -> Optional[str]
Get user's name by ID.
name = db_service.get_name_by_user_id("user123")UserService
Manages user accounts and authentication.
Constructor
UserService(db_service: DatabaseService)Methods
create(name, firstName, lastName, email, password, role, **kwargs) -> User
Create a new user account.
Parameters:
name(str): Full display namefirstName(str): User's first namelastName(str): User's last nameemail(str): Unique email address (login username)password(str): Plain text password (will be hashed)role(str): User role ('patient', 'doctor', 'nurse', 'hospitaladmin', 'family')**kwargs: Additional fields (linkedPatients, etc.)
Returns: Created User object
Example:
user = user_service.create(
name="John Doe",
firstName="John",
lastName="Doe",
email="john@example.com",
password="secure123",
role="patient"
)get_by_id(user_id: str) -> Optional[User]
Get user by ID.
user = user_service.get_by_id("user123")
if user:
print(user.name)get_by_email(email: str) -> Optional[User]
Get user by email address.
user = user_service.get_by_email("john@example.com")authenticate(email: str, password: str) -> Optional[User]
Authenticate user with email and password.
user = user_service.authenticate("john@example.com", "password123")
if user:
print("Login successful")update(user_id: str, **kwargs) -> Optional[User]
Update user fields.
updated_user = user_service.update(
"user123",
name="John Smith",
role="doctor"
)delete(user_id: str) -> bool
Delete user account.
success = user_service.delete("user123")list() -> List[User]
Get all users.
all_users = user_service.list()HealthLogService
Manages daily patient health logs.
Constructor
HealthLogService(db_service: DatabaseService)Methods
create(patientID, physicalStatus, emotionalStatus, symptoms, isSensitive=False) -> HealthLog
Create a new health log entry.
Parameters:
patientID(str): Patient's user IDphysicalStatus(List[str] or str): Physical symptoms/statusemotionalStatus(List[str] or str): Emotional statesymptoms(str): Detailed symptom descriptionisSensitive(bool): Whether to hide from family members
Returns: Created HealthLog object
Example:
log = health_log_service.create(
patientID="patient123",
physicalStatus=["fever", "fatigue"],
emotionalStatus=["anxious"],
symptoms="High fever and headache",
isSensitive=False
)get(log_id: str) -> Optional[HealthLog]
Get health log by ID.
update(log_id: str, **kwargs) -> Optional[HealthLog]
Update health log fields.
delete(log_id: str) -> bool
Delete health log.
list() -> List[HealthLog]
Get all health logs.
get_by_patient(patient_id: str) -> List[HealthLog]
Get all health logs for a specific patient.
patient_logs = health_log_service.get_by_patient("patient123")get_non_sensitive_by_patient(patient_id: str) -> List[HealthLog]
Get only non-sensitive health logs for a patient (used for family member view).
family_viewable = health_log_service.get_non_sensitive_by_patient("patient123")AppointmentService
Manages medical appointments.
Constructor
AppointmentService(db_service: DatabaseService)Methods
create(patientID, reason, requestedDate, status="Pending", **kwargs) -> Appointment
Create appointment request.
Parameters:
patientID(str): Patient requesting appointmentreason(str): Reason for appointmentrequestedDate(str): Requested date/time (ISO format)status(str): Initial status (default: "Pending")**kwargs: Additional fields (doctorID, notes, etc.)
Example:
appointment = appointment_service.create(
patientID="patient123",
reason="Annual checkup",
requestedDate="2025-11-01T10:00:00",
status="Pending"
)assign_doctor(appointment_id: str, doctor_id: str) -> Optional[Appointment]
Assign a doctor to an appointment.
updated = appointment_service.assign_doctor("appt123", "doctor456")update_status(appointment_id: str, status: str) -> Optional[Appointment]
Update appointment status.
Status values: "Pending", "Scheduled", "Completed", "Cancelled"
appointment_service.update_status("appt123", "Completed")get_by_patient(patient_id: str) -> List[Appointment]
Get all appointments for a patient.
get_by_doctor(doctor_id: str) -> List[Appointment]
Get all appointments assigned to a doctor.
get_pending() -> List[Appointment]
Get all pending appointment requests.
pending = appointment_service.get_pending()MedicalRecordService
Manages comprehensive patient medical records.
Constructor
MedicalRecordService(db_service: DatabaseService)Methods
create(patientID, diagnoses=None, prescriptions=None, appointments=None) -> MedicalRecord
Create medical record.
Parameters:
patientID(str): Patient IDdiagnoses(List[str]): List of diagnosis IDsprescriptions(List[str]): List of prescription IDsappointments(List[str]): List of appointment IDs
get_by_patient(patient_id: str) -> Optional[MedicalRecord]
Get complete medical record for patient.
record = medical_record_service.get_by_patient("patient123")
if record:
print(f"Diagnoses: {len(record.diagnoses)}")add_diagnosis(patient_id: str, diagnosis_id: str) -> Optional[MedicalRecord]
Add diagnosis to patient's medical record.
medical_record_service.add_diagnosis("patient123", "diag456")add_prescription(patient_id: str, prescription_id: str) -> Optional[MedicalRecord]
Add prescription to patient's medical record.
add_appointment(patient_id: str, appointment_id: str) -> Optional[MedicalRecord]
Add appointment to patient's medical record.
DiagnosisService
Manages medical diagnoses.
Constructor
DiagnosisService(db_service: DatabaseService)Methods
create(diagnosisID, doctorID, patientID, condition, notes, dateDiagnosed) -> Diagnosis
Create new diagnosis.
Parameters:
diagnosisID(str): Unique diagnosis IDdoctorID(str): Diagnosing doctor's IDpatientID(str): Patient's IDcondition(str): Diagnosed condition/diseasenotes(str): Diagnosis notes and recommendationsdateDiagnosed(str): Date of diagnosis (ISO format)
Example:
diagnosis = diagnosis_service.create(
diagnosisID="diag123",
doctorID="doctor456",
patientID="patient789",
condition="Type 2 Diabetes",
notes="Patient needs lifestyle changes and medication",
dateDiagnosed="2025-10-26"
)get(diagnosis_id: str) -> Optional[Diagnosis]
Get diagnosis by ID.
get_by_patient(patient_id: str) -> List[Diagnosis]
Get all diagnoses for a patient.
patient_diagnoses = diagnosis_service.get_by_patient("patient123")get_by_doctor(doctor_id: str) -> List[Diagnosis]
Get all diagnoses made by a doctor.
PrescriptionService
Manages medication prescriptions.
Constructor
PrescriptionService(db_service: DatabaseService)Methods
create(prescriptionID, doctorID, patientID, medication, dosage, instruction, datePrescribed) -> Prescription
Create new prescription.
Parameters:
prescriptionID(str): Unique prescription IDdoctorID(str): Prescribing doctor's IDpatientID(str): Patient's IDmedication(str): Medication namedosage(str): Dosage amount (e.g., "500mg")instruction(str): Administration instructionsdatePrescribed(str): Prescription date (ISO format)
Example:
prescription = prescription_service.create(
prescriptionID="presc123",
doctorID="doctor456",
patientID="patient789",
medication="Metformin",
dosage="500mg",
instruction="Take twice daily with meals",
datePrescribed="2025-10-26"
)get(prescription_id: str) -> Optional[Prescription]
Get prescription by ID.
get_by_patient(patient_id: str) -> List[Prescription]
Get all prescriptions for a patient.
get_active_prescriptions(patient_id: str) -> List[Prescription]
Get active/current prescriptions for a patient.
EmergencyCallService
Manages emergency care requests.
Constructor
EmergencyCallService(db_service: DatabaseService)Methods
create(emergency_call: EmergencyCall) -> EmergencyCall
Create emergency call.
Parameters:
emergency_call(EmergencyCall): Emergency call object
Example:
from core.models.emergency_call import EmergencyCall
import datetime
call = EmergencyCall(
callID="call123",
patientID="patient456",
timestamp=datetime.datetime.now().isoformat(),
urgencyLevel="HIGH",
isResolved=False,
isEscalated=False
)
created = emergency_call_service.create(call)get_unresolved() -> List[EmergencyCall]
Get all unresolved emergency calls.
pending_calls = emergency_call_service.get_unresolved()get_by_patient(patient_id: str) -> List[EmergencyCall]
Get all emergency calls from a patient.
respond_to_call(call_id: str, responder_id: str) -> Optional[EmergencyCall]
Mark emergency call as resolved with responder.
emergency_call_service.respond_to_call("call123", "nurse456")escalate_call(call_id: str) -> Optional[EmergencyCall]
Escalate emergency call to doctor.
emergency_call_service.escalate_call("call123")get_escalated() -> List[EmergencyCall]
Get all escalated emergency calls.
NotificationService
Manages system notifications.
Constructor
NotificationService(db_service: DatabaseService)Methods
create(notificationID, userID, message, timestamp, isRead="unread") -> Notification
Create notification.
Parameters:
notificationID(str): Unique notification IDuserID(str): Recipient user IDmessage(str): Notification messagetimestamp(str): Creation timestamp (ISO format)isRead(str): Read status ("unread" or "read")
Example:
notification = notification_service.create(
notificationID="notif123",
userID="user456",
message="Your appointment is confirmed",
timestamp="2025-10-26T10:00:00",
isRead="unread"
)get_by_user(user_id: str) -> List[Notification]
Get all notifications for a user.
user_notifications = notification_service.get_by_user("user123")get_unread(user_id: str) -> List[Notification]
Get unread notifications for a user.
mark_as_read(notification_id: str) -> Optional[Notification]
Mark notification as read.
notification_service.mark_as_read("notif123")VisitRequestService
Manages family visit requests.
Constructor
VisitRequestService(db_service: DatabaseService)Methods
create(patientID, familyMemberID, requestedDate, status) -> VisitRequest
Create visit request.
Parameters:
patientID(str): Patient being visitedfamilyMemberID(str): Requesting family memberrequestedDate(str): Requested visit date/timestatus(str): Request status ("Submitted", "Approved", "Denied")
Example:
visit = visit_request_service.create(
patientID="patient123",
familyMemberID="family456",
requestedDate="2025-10-27T14:00:00",
status="Submitted"
)get_by_patient(patient_id: str) -> List[VisitRequest]
Get all visit requests for a patient.
get_by_family_member(family_id: str) -> List[VisitRequest]
Get all visit requests from a family member.
approve_request(request_id: str) -> Optional[VisitRequest]
Approve visit request.
visit_request_service.approve_request("visit123")deny_request(request_id: str) -> Optional[VisitRequest]
Deny visit request.
AuditLogService
Manages system audit logs.
Constructor
AuditLogService(db_service: DatabaseService)Methods
create(logID, userID, action, timestamp, details) -> AuditLog
Create audit log entry.
Parameters:
logID(str): Unique log IDuserID(str): User who performed actionaction(str): Action performedtimestamp(str): Action timestamp (ISO format)details(str): Detailed description
Example:
audit_log_service.create(
logID="log123",
userID="user456",
action="LOGIN",
timestamp="2025-10-26T10:00:00",
details="User logged in successfully"
)get_by_user(user_id: str) -> List[AuditLog]
Get all audit logs for a user.
get_by_action(action: str) -> List[AuditLog]
Get all audit logs of a specific action type.
list() -> List[AuditLog]
Get all audit logs.
FeedbackService
Manages user feedback.
Constructor
FeedbackService(db_service: DatabaseService)Methods
create(userID, category, message, timestamp) -> Feedback
Create feedback entry.
Parameters:
userID(str): User submitting feedbackcategory(str): Feedback categorymessage(str): Feedback messagetimestamp(str): Submission timestamp (ISO format)
Example:
feedback = feedback_service.create(
userID="user123",
category="Service Quality",
message="Great experience with the nursing staff!",
timestamp="2025-10-26T10:00:00"
)get_by_user(user_id: str) -> List[Feedback]
Get all feedback from a user.
get_by_category(category: str) -> List[Feedback]
Get all feedback of a specific category.
Utility Functions
Authentication (core.utils.auth)
PasswordHash
Password hashing utility using Argon2.
from core.utils.auth import PasswordHash
hasher = PasswordHash()
# Hash password
hashed = hasher.hash("mypassword")
# Verify password
is_valid = hasher.verify("mypassword", hashed) # Returns TrueTime Formatting (core.utils.timeformat)
to_readable(iso_timestamp: str) -> str
Convert ISO timestamp to readable format.
from core.utils.timeformat import to_readable
readable = to_readable("2025-10-26T10:00:00")
# Returns: "October 26, 2025 10:00 AM"time_ago(iso_timestamp: str) -> str
Convert ISO timestamp to relative time.
from core.utils.timeformat import time_ago
relative = time_ago("2025-10-26T10:00:00")
# Returns: "2 hours ago"Error Handling
All service methods that return Optional[T] will return None if the requested item is not found. Always check for None before accessing attributes:
user = user_service.get_by_id("user123")
if user is not None:
print(user.name)
else:
print("User not found")