Hospital Management System

Base URL

Production: http://localhost:8000/api
API Version: 1.0
Status: Production Ready

Authentication

POST /auth/login Public

Authenticate user and receive access token for subsequent API requests.

Request Body:

{
  "email": "admin@hospital.com",
  "password": "SecurePass123!@"
}

Success Response (200):

{
  "success": true,
  "token": "1|abcdefghijklmnopqrstuvwxyz123456",
  "user": {
    "id": 1,
    "name": "Admin User",
    "email": "admin@hospital.com",
    "role": "admin",
    "phone": "+1234567890"
  }
}

cURL Example:

curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@hospital.com","password":"SecurePass123!@"}'
Important: All subsequent requests must include the token in the Authorization header:
Authorization: Bearer YOUR_TOKEN_HERE

Users & Invitations

List Users

GET /users Auth Required Admin Only

Retrieve a list of all users in the system.

cURL Example:

curl http://localhost:8000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Create Invitation

POST /invitations Auth Required Admin Only

Create an invitation for a new user to join the system.

Request Body:

{
  "email": "newdoctor@hospital.com",
  "role": "doctor"
}

Available Roles:

admin, doctor, receptionist, cashier, nurse, lab_technician, pharmacist

cURL Example:

curl -X POST http://localhost:8000/api/invitations \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"email":"newdoctor@hospital.com","role":"doctor"}'

Accept Invitation

POST /invitations/{token}/accept Public

Accept an invitation and complete user registration.

Request Body:

{
  "password": "SecurePass123!@",
  "name": "Dr. John Doe",
  "phone": "+1234567890"
}

Password Requirements:

• Minimum 8 characters
• At least one uppercase letter
• At least one lowercase letter
• At least one number
• At least one special character (!@#$%^&*)

cURL Example:

curl -X POST http://localhost:8000/api/invitations/abc123xyz789/accept \
  -H "Content-Type: application/json" \
  -d '{"password":"SecurePass123!@","name":"Dr. John Doe","phone":"+1234567890"}'

🏥 Patients

List Patients

GET /patients Auth Required

Retrieve a paginated list of patients with optional search and filtering.

Query Parameters:

?search=John - Search by name, email, or phone
?per_page=20 - Results per page (default: 15)
?page=2 - Page number

cURL Example:

curl "http://localhost:8000/api/patients?search=John&per_page=15" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Create Patient

POST /patients Auth Required

Register a new patient in the system.

Request Body:

{
  "first_name": "John",
  "last_name": "Doe",
  "date_of_birth": "1990-01-15",
  "gender": "male",
  "phone": "+1234567890",
  "email": "john@example.com",
  "blood_group": "O+",
  "allergies": ["Penicillin", "Peanuts"],
  "medical_history": "Diabetes Type 2, Hypertension"
}

cURL Example:

curl -X POST http://localhost:8000/api/patients \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"first_name":"John","last_name":"Doe","date_of_birth":"1990-01-15","gender":"male","phone":"+1234567890"}'

Get Patient Visits

GET /patients/{id}/visits Auth Required

Retrieve all visit records for a specific patient.

cURL Example:

curl http://localhost:8000/api/patients/1/visits \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

📅 Appointments

List Appointments

GET /appointments Auth Required

Retrieve a paginated list of appointments with optional filtering.

Query Parameters:

?status=scheduled - Filter by status (scheduled, completed, cancelled)
?doctor_id=2 - Filter by doctor
?per_page=15 - Results per page

cURL Example:

curl "http://localhost:8000/api/appointments?status=scheduled&doctor_id=2" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Create Appointment

POST /appointments Auth Required

Schedule a new appointment for a patient.

Request Body:

{
  "patient_id": 1,
  "doctor_id": 2,
  "appointment_date": "2025-01-20",
  "appointment_time": "14:30",
  "reason": "Regular checkup",
  "notes": "Patient prefers morning appointments"
}

cURL Example:

curl -X POST http://localhost:8000/api/appointments \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"patient_id":1,"doctor_id":2,"appointment_date":"2025-01-20","appointment_time":"14:30","reason":"Regular checkup"}'

Cancel Appointment

PATCH /appointments/{id}/cancel Auth Required

Cancel an existing appointment.

cURL Example:

curl -X PATCH http://localhost:8000/api/appointments/1/cancel \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

🩺 Visits (EMR)

List Visits

GET /visits Auth Required

Retrieve a paginated list of visit records.

Query Parameters:

?patient_id=1 - Filter by patient
?doctor_id=2 - Filter by doctor
?per_page=15 - Results per page

cURL Example:

curl "http://localhost:8000/api/visits?patient_id=1&doctor_id=2" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Create Visit Record

POST /visits Auth Required

Create a new visit record (Electronic Medical Record).

Request Body:

{
  "patient_id": 1,
  "doctor_id": 2,
  "appointment_id": 1,
  "visit_date": "2025-01-20",
  "chief_complaint": "Chest pain",
  "diagnosis": "Angina pectoris",
  "medical_notes": "Patient reports intermittent chest pain...",
  "vital_signs": {
    "blood_pressure": "120/80",
    "temperature": "98.6",
    "pulse": "72",
    "weight": "70"
  },
  "consultation_fee": 50.00
}

cURL Example:

curl -X POST http://localhost:8000/api/visits \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"patient_id":1,"doctor_id":2,"visit_date":"2025-01-20","chief_complaint":"Chest pain","diagnosis":"Angina pectoris","consultation_fee":50.00}'

🧪 Lab Tests

Create Lab Order

POST /labs/orders Auth Required

Create a new laboratory test order.

Request Body:

{
  "patient_id": 1,
  "doctor_id": 2,
  "visit_id": 1,
  "test_name": "Complete Blood Count",
  "test_type": "Blood Test",
  "priority": "normal",
  "notes": "Fasting required",
  "order_date": "2025-01-20",
  "cost": 25.00
}

cURL Example:

curl -X POST http://localhost:8000/api/labs/orders \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"patient_id":1,"doctor_id":2,"test_name":"Complete Blood Count","test_type":"Blood Test","priority":"normal","cost":25.00}'

Upload Lab Result

POST /labs/results Auth Required

Upload laboratory test results.

Request Body:

{
  "lab_order_id": 1,
  "results": "All values within normal range",
  "result_file_url": "https://example.com/results/file.pdf",
  "result_date": "2025-01-21",
  "notes": "No abnormalities detected"
}

cURL Example:

curl -X POST http://localhost:8000/api/labs/results \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"lab_order_id":1,"results":"All values within normal range","result_date":"2025-01-21"}'

Pharmacy

Create Prescription

POST /pharmacy/prescriptions Auth Required

Create a new prescription for a patient.

Request Body:

{
  "patient_id": 1,
  "doctor_id": 2,
  "visit_id": 1,
  "prescription_date": "2025-01-20",
  "medications": [
    {
      "name": "Aspirin",
      "dosage": "500mg",
      "frequency": "Twice daily",
      "duration": "7 days",
      "instructions": "Take with food"
    },
    {
      "name": "Metformin",
      "dosage": "850mg",
      "frequency": "Three times daily",
      "duration": "30 days",
      "instructions": "With meals"
    }
  ],
  "notes": "Follow up after 2 weeks"
}

cURL Example:

curl -X POST http://localhost:8000/api/pharmacy/prescriptions \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"patient_id":1,"doctor_id":2,"prescription_date":"2025-01-20","medications":[{"name":"Aspirin","dosage":"500mg","frequency":"Twice daily","duration":"7 days"}]}'

List Prescriptions

GET /pharmacy/prescriptions Auth Required

Retrieve a paginated list of prescriptions with optional filtering.

Query Parameters:

?status=pending - Filter by status (pending, dispensed, cancelled)
?patient_id=1 - Filter by patient
?per_page=15 - Results per page

cURL Example:

curl "http://localhost:8000/api/pharmacy/prescriptions?status=pending&per_page=15" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Update Prescription Status

PUT /pharmacy/prescriptions/{id} Auth Required

Update prescription status (mark as dispensed, cancelled, etc).

Request Body:

{
  "status": "dispensed",
  "notes": "Dispensed on 2025-01-21"
}

cURL Example:

curl -X PUT http://localhost:8000/api/pharmacy/prescriptions/1 \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"status":"dispensed","notes":"Dispensed on 2025-01-21"}'

✉️ Email Notification:

When status changes to dispensed, the system automatically sends a Prescription Ready email to the patient with medication details and pickup instructions.

Get Pharmacy Inventory

GET /pharmacy/inventory Auth Required

Retrieve current pharmacy inventory with stock levels.

Query Parameters:

?low_stock=true - Show only low stock items
?expired=true - Show expired items
?per_page=15 - Results per page

cURL Example:

curl "http://localhost:8000/api/pharmacy/inventory?low_stock=true" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Billing & Invoices

Create Invoice

POST /invoices Auth Required

Create a new invoice for a patient visit or services.

Request Body:

{
  "patient_id": 1,
  "visit_id": 1,
  "invoice_date": "2025-01-20",
  "items": [
    {
      "description": "Doctor Consultation",
      "quantity": 1,
      "unit_price": 50.00,
      "amount": 50.00
    },
    {
      "description": "Blood Test (CBC)",
      "quantity": 1,
      "unit_price": 25.00,
      "amount": 25.00
    },
    {
      "description": "Medications",
      "quantity": 1,
      "unit_price": 35.00,
      "amount": 35.00
    }
  ],
  "subtotal": 110.00,
  "tax": 11.00,
  "discount": 0.00,
  "total": 121.00
}

cURL Example:

curl -X POST http://localhost:8000/api/invoices \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"patient_id":1,"visit_id":1,"invoice_date":"2025-01-20","subtotal":110.00,"tax":11.00,"total":121.00}'

Email Notification:

When an invoice is created, the system automatically sends an Invoice Created email to the patient with itemized details, total amount due, and payment methods.

List Invoices

GET /invoices Auth Required

Retrieve a paginated list of invoices with optional filtering.

Query Parameters:

?status=pending - Filter by status (pending, paid, cancelled)
?patient_id=1 - Filter by patient
?per_page=15 - Results per page

cURL Example:

curl "http://localhost:8000/api/invoices?status=pending&per_page=15" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"

Mark Invoice as Paid

PATCH /invoices/{id}/pay Auth Required

Mark an invoice as paid and record payment details.

Request Body:

{
  "payment_method": "card",
  "amount_paid": 121.00,
  "payment_date": "2025-01-20"
}

Payment Methods:

cash | card | insurance | other

cURL Example:

curl -X PATCH http://localhost:8000/api/invoices/1/pay \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"payment_method":"card","amount_paid":121.00,"payment_date":"2025-01-20"}'

Email Notification:

When payment is received, the system automatically sends an Invoice Paid email to the patient with payment confirmation, date, and receipt reference number.

Response Formats

Success Response Format

{
  "success": true,
  "message": "Operation completed successfully",
  "data": {
    "id": 1,
    "name": "John Doe",
    "email": "john@example.com",
    ...
  }
}

Paginated Response Format

{
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "John Doe",
      ...
    }
  ],
  "meta": {
    "total": 100,
    "per_page": 15,
    "current_page": 1,
    "last_page": 7,
    "from": 1,
    "to": 15
  },
  "links": {
    "first": "http://localhost:8000/api/patients?page=1",
    "last": "http://localhost:8000/api/patients?page=7",
    "next": "http://localhost:8000/api/patients?page=2"
  }
}

Error Response Format

{
  "success": false,
  "message": "Validation error",
  "errors": {
    "email": ["The email field is required"],
    "password": ["The password must be at least 8 characters"]
  }
}

HTTP Status Codes

Code Meaning Description
200 OK Request successful
201 Created Resource created successfully
400 Bad Request Invalid request parameters
401 Unauthorized Missing or invalid authentication token
403 Forbidden User lacks required permissions
404 Not Found Resource does not exist
422 Unprocessable Entity Validation failed
500 Server Error Internal server error

Roles & Permissions

Available Roles

Role Description Key Permissions
Admin Full system access All operations, user management, system configuration
Doctor Medical professional Create visits, prescriptions, lab orders, view patients
Receptionist Front desk staff Manage appointments, patient registration
Cashier Billing staff Create invoices, process payments, view billing
Nurse Nursing staff Record vital signs, assist doctors, view patient info
Lab Technician Laboratory staff Create lab orders, upload results, manage tests
Pharmacist Pharmacy staff Dispense prescriptions, manage inventory

Role-Based Access Control

Note: All endpoints (except login and invitation acceptance) require authentication. Access is restricted based on user role. Some endpoints require specific roles as documented in each endpoint section.

Bearer Token Usage

Include your authentication token in the Authorization header for all requests:

Authorization: Bearer YOUR_TOKEN_HERE

Example with Headers:

curl http://localhost:8000/api/patients \
  -H "Authorization: Bearer 1|abcdefghijklmnopqrstuvwxyz123456" \
  -H "Accept: application/json"

Additional Resources

Error Handling Best Practices

Always check the response status:
• Check the success field in JSON response
• Inspect HTTP status codes
• Read error messages for debugging
• Implement proper error handling in your client application

Email Notifications

Automatic Email System:
The system automatically sends professional emails for:
Appointments: Confirmation and cancellation notices
Lab Results: Notifications when results are ready
Prescriptions: Alerts when ready for pickup
Invoices: Billing notifications and payment confirmations

Emails are sent to the patient's registered email address with professional HTML templates.

Rate Limiting

Current Configuration:
• Rate limit: 60 requests per minute per user
• Burst limit: 100 requests per 5 minutes
• Reset: Automatic reset every minute
Contact administrator for higher limits if needed.

Data Validation Rules

Field Type Rules Example
Email Valid email format user@example.com
Phone 10-15 digits, optional + +1234567890
Date YYYY-MM-DD format 2025-01-20
Time HH:MM format (24hr) 14:30
Money Decimal, 2 places max 99.99
Password Min 8 chars, mixed case, special char SecurePass123!@

Common Issues & Solutions

401 Unauthorized: Token expired or invalid. Re-authenticate with login endpoint.

403 Forbidden: User role lacks permission for this endpoint. Use appropriate user role.

422 Validation Error: Check request data against schema. Review error messages in response.

500 Server Error: Contact system administrator. Check server logs.

Support & Contact

Documentation Version: 1.0
Last Updated: January 2026
API Status: Fully Operational
Server: http://localhost:8000

For Support:
Email: support@afyamed.com
Website: DevConnectTz
Phone: +255 (0)XXX XXX XXX

Getting Started Checklist

Review this documentation
Set up your development environment
Get API credentials from administrator
Authenticate to get token via login endpoint
Test endpoints with provided cURL examples
Implement error handling in your application
Monitor email notifications
Deploy to production