---
type: Reference
title: Readme
description: >-
  Complete REST API Documentation for KiviCare Healthcare Management System
timestamp: 2025-09-14T03:15:35.167510+00:00
layer: wiki
---
# 🏥 Care API Documentation

**Complete REST API Documentation for KiviCare Healthcare Management System**

<div align="center">

[![API Version](https://img.shields.io/badge/API%20Version-1.0.0-blue)](https://github.com/descomplicar/care-api)
[![Endpoints](https://img.shields.io/badge/Endpoints-84-green)](#endpoints-overview)
[![OpenAPI](https://img.shields.io/badge/OpenAPI-3.0.3-orange)](care-api-complete-openapi.yaml)
[![Made by](https://img.shields.io/badge/Made%20by-Descomplicar®-purple)](https://descomplicar.pt)

[📚 Interactive Explorer](#interactive-api-explorer) • [🗺️ Complete Map](#complete-endpoint-map) • [📋 Postman Collection](#postman-collection) • [⚡ Quick Start](#quick-start)

</div>

## 📋 Table of Contents

- [Overview](#overview)
- [Quick Start](#quick-start)
- [Interactive API Explorer](#interactive-api-explorer)
- [Documentation Files](#documentation-files)
- [Endpoints Overview](#endpoints-overview)
- [Authentication](#authentication)
- [Response Format](#response-format)
- [Error Handling](#error-handling)
- [Rate Limiting](#rate-limiting)
- [Testing](#testing)
- [Development Setup](#development-setup)
- [Contributing](#contributing)

## 🔍 Overview

The **Care API** is a comprehensive REST API for healthcare management built on top of the WordPress REST API framework and integrated with the KiviCare healthcare management system. It provides secure access to manage clinics, patients, doctors, appointments, medical encounters, prescriptions, and billing.

### ✨ Key Features

- **🔐 JWT Authentication** - Secure token-based authentication with refresh tokens
- **📊 84 REST Endpoints** - Complete healthcare management functionality
- **⚡ Rate Limiting** - Built-in protection against abuse
- **🏥 Multi-clinic Support** - Isolated data per clinic
- **📱 Mobile-Ready** - RESTful design perfect for mobile apps
- **🔒 Role-based Access** - Admin, Doctor, Receptionist, Patient roles
- **📈 Real-time Analytics** - Dashboard and statistics endpoints
- **💊 Medical Features** - SOAP notes, prescriptions, drug interactions
- **💰 Billing System** - Complete invoicing and payment tracking

### 🎯 Use Cases

- **Hospital Management Systems** - Complete clinic operations
- **Mobile Health Apps** - Patient portals and doctor apps
- **Telemedicine Platforms** - Remote consultations and prescriptions
- **Medical Dashboards** - Analytics and reporting systems
- **Integration Projects** - Connect with external healthcare systems

## ⚡ Quick Start

### 1. Prerequisites

- WordPress 5.0+
- PHP 8.1+
- KiviCare Plugin installed and activated
- Care API Plugin installed

### 2. Authentication

```bash
# 1. Login to get JWT token
curl -X POST "https://your-domain.com/wp-json/care/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "your_username", "password": "your_password"}'
```

Response:
```json
{
  "success": true,
  "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "expires_in": 86400,
    "user": { "id": 123, "role": "doctor", ... }
  }
}
```

### 3. Making Authenticated Requests

```bash
# Use the token in Authorization header
curl -X GET "https://your-domain.com/wp-json/care/v1/clinics" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

### 4. Basic Operations

```bash
# Get all patients
GET /patients?page=1&per_page=20

# Create new appointment
POST /appointments
{
  "doctor_id": 456,
  "patient_id": 789,
  "appointment_date": "2025-09-20",
  "appointment_time": "10:30:00",
  "duration": 30,
  "reason": "Regular checkup"
}

# Get clinic dashboard
GET /clinics/1/dashboard?period=month
```

## 🚀 Interactive API Explorer

**Open the interactive documentation in your browser:**

```bash
# Option 1: Direct file access
open docs/api-explorer.html

# Option 2: Serve with local web server
cd docs/
python3 -m http.server 8080
# Then open: http://localhost:8080/api-explorer.html
```

### Features

- **📖 Complete API Documentation** - All 84 endpoints documented
- **🧪 Interactive Testing** - Try requests directly from the browser
- **🔐 JWT Authentication** - Built-in token management
- **📊 Real-time Examples** - See actual request/response data
- **🎨 Beautiful UI** - Powered by Swagger UI with custom Care API styling

![API Explorer Screenshot](api-explorer-screenshot.png)

## 📁 Documentation Files

This documentation package includes:

| File | Description | Use Case |
|------|-------------|----------|
| [`api-explorer.html`](api-explorer.html) | **Interactive Documentation** | Browse and test all endpoints |
| [`care-api-complete-openapi.yaml`](care-api-complete-openapi.yaml) | **OpenAPI 3.0 Specification** | Generate SDKs, import to tools |
| [`API_ENDPOINTS_COMPLETE_MAP.md`](../API_ENDPOINTS_COMPLETE_MAP.md) | **Complete Endpoint Map** | Reference guide for all endpoints |
| [`Care-API-Postman-Collection.json`](Care-API-Postman-Collection.json) | **Postman Collection** | Ready-to-use test collection |
| [`README.md`](README.md) | **This Documentation** | Getting started guide |

## 📊 Endpoints Overview

<div align="center">

| Category | Endpoints | Description |
|----------|-----------|-------------|
| **🔐 Authentication** | 8 | Login, logout, tokens, password reset |
| **🏥 Clinics** | 9 | Clinic management, dashboard, statistics |
| **👥 Patients** | 7 | Patient records, medical history |
| **👨‍⚕️ Doctors** | 10 | Doctor profiles, schedules, statistics |
| **📅 Appointments** | 9 | Scheduling, availability, management |
| **🏥 Encounters** | 13 | Medical consultations, SOAP, vitals |
| **💊 Prescriptions** | 12 | Prescriptions, interactions, renewals |
| **💰 Bills** | 14 | Billing, payments, financial reports |
| **🔧 Utilities** | 3 | System status, health checks, version |

**Total: 84 REST Endpoints**

</div>

### 🏆 Most Used Endpoints

```bash
# Authentication
POST /auth/login              # User login
POST /auth/logout             # User logout
GET  /auth/profile            # Get user profile

# Core Operations
GET  /clinics                 # List clinics
GET  /patients/search         # Search patients
POST /appointments            # Create appointment
GET  /appointments/availability/{doctor_id}  # Check availability

# Medical Operations
POST /encounters              # Create medical encounter
PUT  /encounters/{id}/soap    # Update SOAP notes
POST /prescriptions           # Create prescription
GET  /bills/overdue          # Get overdue bills
```

## 🔐 Authentication

The Care API uses **JWT (JSON Web Tokens)** for secure authentication.

### Token Lifecycle

1. **Login** → Get access token (24h) + refresh token (7d)
2. **Use** → Include `Authorization: Bearer <token>` in requests
3. **Refresh** → Use refresh token to get new access token
4. **Logout** → Invalidate tokens

### Example Flow

```javascript
// 1. Login
const loginResponse = await fetch('/wp-json/care/v1/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    username: 'doctor_smith',
    password: 'secure_password'
  })
});

const { data } = await loginResponse.json();
const accessToken = data.token;

// 2. Make authenticated requests
const patientsResponse = await fetch('/wp-json/care/v1/patients', {
  headers: { 'Authorization': `Bearer ${accessToken}` }
});

// 3. Refresh token when needed
const refreshResponse = await fetch('/wp-json/care/v1/auth/refresh', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${accessToken}`
  },
  body: JSON.stringify({
    refresh_token: data.refresh_token
  })
});
```

## 📄 Response Format

All API responses follow a consistent structure:

### Success Response (HTTP 2xx)
```json
{
  "success": true,
  "data": {
    // Response data varies by endpoint
  },
  "message": "Operation completed successfully",
  "timestamp": "2025-09-14T10:30:00Z",
  "pagination": {  // Only for paginated responses
    "current_page": 1,
    "per_page": 20,
    "total": 150,
    "total_pages": 8
  }
}
```

### Error Response (HTTP 4xx/5xx)
```json
{
  "success": false,
  "message": "Error description",
  "error_code": "VALIDATION_ERROR",
  "errors": {  // Field-specific errors when applicable
    "email": ["The email field must be a valid email address"],
    "phone": ["The phone field is required"]
  },
  "timestamp": "2025-09-14T10:30:00Z"
}
```

## ⚠️ Error Handling

### Common HTTP Status Codes

| Code | Description | Common Causes |
|------|-------------|---------------|
| `200` | Success | Request completed successfully |
| `201` | Created | Resource created successfully |
| `400` | Bad Request | Invalid input data, validation errors |
| `401` | Unauthorized | Missing or invalid authentication token |
| `403` | Forbidden | Insufficient permissions for the operation |
| `404` | Not Found | Requested resource does not exist |
| `422` | Unprocessable Entity | Valid JSON but business logic errors |
| `429` | Too Many Requests | Rate limit exceeded |
| `500` | Internal Server Error | Server-side error |
| `503` | Service Unavailable | System maintenance or dependencies down |

### Error Codes Reference

| Error Code | Description | Resolution |
|------------|-------------|------------|
| `VALIDATION_ERROR` | Input validation failed | Check `errors` field for specific issues |
| `UNAUTHORIZED` | Authentication required | Provide valid JWT token |
| `FORBIDDEN` | Insufficient permissions | Contact admin for role permissions |
| `NOT_FOUND` | Resource not found | Verify resource ID exists |
| `RATE_LIMIT_EXCEEDED` | Too many requests | Wait and retry, check rate limits |
| `CLINIC_ISOLATION_ERROR` | Cross-clinic access denied | Access only your clinic's data |
| `APPOINTMENT_CONFLICT` | Time slot unavailable | Choose different time slot |
| `PRESCRIPTION_INTERACTION` | Drug interaction detected | Review medication compatibility |

## ⏱️ Rate Limiting

The API implements rate limiting to ensure fair usage and system stability:

### Rate Limits by Endpoint Type

| Endpoint Category | Limit | Window | Notes |
|------------------|-------|---------|-------|
| **Authentication** | 10 requests | 1 hour | Per IP address |
| **General API** | 1000 requests | 1 hour | Per JWT token |
| **Health Check** | 60 requests | 1 minute | Per IP address |
| **Search Operations** | 100 requests | 15 minutes | Per JWT token |
| **Bulk Operations** | 10 requests | 1 hour | Per JWT token |

### Rate Limit Headers

```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1642678800
```

### Handling Rate Limits

```javascript
const response = await fetch('/wp-json/care/v1/patients');

if (response.status === 429) {
  const resetTime = response.headers.get('X-RateLimit-Reset');
  const waitTime = (resetTime * 1000) - Date.now();

  console.log(`Rate limited. Retry after ${waitTime}ms`);
  setTimeout(() => {
    // Retry request
  }, waitTime);
}
```

## 🧪 Testing

### Option 1: Postman Collection

1. **Import Collection**
   ```bash
   # Download the collection
   curl -O "Care-API-Postman-Collection.json"
   ```

2. **Set Environment Variables**
   - `baseUrl`: `http://localhost/wp-json/care/v1`
   - `username`: Your WordPress username
   - `password`: Your WordPress password

3. **Run Authentication** → Other requests automatically use the saved token

### Option 2: Interactive Explorer

1. **Open API Explorer**
   ```bash
   open docs/api-explorer.html
   ```

2. **Authenticate** → Use the "Authorize" button in Swagger UI
3. **Test Endpoints** → Click "Try it out" on any endpoint

### Option 3: Command Line

```bash
# Set your API base URL
BASE_URL="http://localhost/wp-json/care/v1"

# Login and save token
TOKEN=$(curl -s -X POST "$BASE_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}' \
  | jq -r '.data.token')

# Test endpoints
curl -H "Authorization: Bearer $TOKEN" "$BASE_URL/clinics"
curl -H "Authorization: Bearer $TOKEN" "$BASE_URL/patients/search?search=john"
```

### Option 4: JavaScript/Node.js

```javascript
class CareAPIClient {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.token = null;
  }

  async login(username, password) {
    const response = await fetch(`${this.baseUrl}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });

    const data = await response.json();
    this.token = data.data.token;
    return data;
  }

  async request(endpoint, options = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json',
        ...options.headers
      }
    });

    return response.json();
  }

  // Convenience methods
  async getClinics(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(`/clinics?${query}`);
  }

  async createAppointment(data) {
    return this.request('/appointments', {
      method: 'POST',
      body: JSON.stringify(data)
    });
  }
}

// Usage
const api = new CareAPIClient('http://localhost/wp-json/care/v1');
await api.login('admin', 'password');

const clinics = await api.getClinics({ status: 'active' });
console.log('Active clinics:', clinics);
```

## 🛠️ Development Setup

### Local Development

1. **WordPress Setup**
   ```bash
   # Install WordPress
   wp core download
   wp config create --dbname=careapi --dbuser=root --dbpass=password
   wp core install --url=http://localhost --title="Care API Dev"

   # Install KiviCare plugin
   wp plugin install kivicare-clinic-&-patient-management-system
   wp plugin activate kivicare-clinic-&-patient-management-system
   ```

2. **Install Care API Plugin**
   ```bash
   # Copy plugin to WordPress plugins directory
   cp -r care-api-plugin wp-content/plugins/care-api
   wp plugin activate care-api
   ```

3. **Configure Environment**
   ```php
   // wp-config.php
   define('CARE_API_DEBUG', true);
   define('CARE_API_JWT_SECRET', 'your-super-secure-secret');
   define('WP_DEBUG', true);
   ```

4. **Test Installation**
   ```bash
   # Health check
   curl http://localhost/wp-json/care/v1/health

   # Should return: {"status":"healthy","timestamp":"..."}
   ```

### Production Deployment

1. **Security Configuration**
   ```php
   // wp-config.php
   define('CARE_API_DEBUG', false);
   define('CARE_API_JWT_SECRET', wp_generate_password(64, true, true));
   define('CARE_API_RATE_LIMIT', 1000); // requests per hour
   ```

2. **Web Server Configuration**
   ```nginx
   # nginx.conf - Enable CORS for API
   location /wp-json/care/v1/ {
     add_header Access-Control-Allow-Origin *;
     add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS";
     add_header Access-Control-Allow-Headers "Authorization, Content-Type";
   }
   ```

3. **SSL Certificate**
   ```bash
   # Use Let's Encrypt for HTTPS
   certbot --nginx -d your-domain.com
   ```

4. **Monitoring Setup**
   ```bash
   # Health check monitoring
   */5 * * * * curl -f http://your-domain.com/wp-json/care/v1/health || mail -s "API Down" admin@yourdomain.com
   ```

## 🚀 Advanced Usage

### SDK Generation

Generate client SDKs from the OpenAPI specification:

```bash
# JavaScript/TypeScript SDK
openapi-generator-cli generate \
  -i docs/care-api-complete-openapi.yaml \
  -g typescript-fetch \
  -o sdk/typescript

# PHP SDK
openapi-generator-cli generate \
  -i docs/care-api-complete-openapi.yaml \
  -g php \
  -o sdk/php

# Python SDK
openapi-generator-cli generate \
  -i docs/care-api-complete-openapi.yaml \
  -g python \
  -o sdk/python
```

### Webhook Integration

```php
// Custom webhook for appointment changes
add_action('care_api_appointment_created', function($appointment) {
    wp_remote_post('https://your-system.com/webhooks/appointment-created', [
        'body' => json_encode($appointment),
        'headers' => ['Content-Type' => 'application/json']
    ]);
});
```

### Custom Endpoints

```php
// Add custom endpoint to the API
add_action('rest_api_init', function() {
    register_rest_route('care/v1', '/custom/reports', [
        'methods' => 'GET',
        'callback' => 'generate_custom_report',
        'permission_callback' => function() {
            return current_user_can('manage_options');
        }
    ]);
});
```

## 📞 Support & Contributing

### 🆘 Getting Help

- **📧 Email Support**: [dev@descomplicar.pt](mailto:dev@descomplicar.pt)
- **💬 Discord**: [Descomplicar Developer Community](https://discord.gg/descomplicar)
- **📖 Knowledge Base**: [docs.descomplicar.pt](https://docs.descomplicar.pt)
- **🐛 Bug Reports**: [GitHub Issues](https://github.com/descomplicar/care-api/issues)

### 🤝 Contributing

1. **Fork** the repository
2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
3. **Commit** your changes: `git commit -m 'Add amazing feature'`
4. **Push** to branch: `git push origin feature/amazing-feature`
5. **Open** a Pull Request

### 📋 Contribution Guidelines

- Follow WordPress coding standards
- Write unit tests for new features
- Update documentation for API changes
- Use semantic commit messages
- Test with multiple WordPress/PHP versions

## 📜 License

This project is licensed under the **GPL v3 License** - see the [LICENSE](LICENSE) file for details.

## 🏆 Credits

**Developed with ❤️ by [Descomplicar® Crescimento Digital](https://descomplicar.pt)**

- **Architecture**: WordPress REST API Framework
- **Healthcare Integration**: KiviCare Plugin
- **Authentication**: JWT (JSON Web Tokens)
- **Documentation**: OpenAPI 3.0 + Swagger UI
- **Testing**: Postman Collections

### 🌟 Special Thanks

- WordPress REST API Team
- KiviCare Plugin Developers
- OpenAPI Initiative
- Swagger UI Contributors
- The entire open-source community

---

<div align="center">

**🏥 Care API v1.0.0** | **Made in Portugal** 🇵🇹

[![Descomplicar](https://img.shields.io/badge/Powered%20by-Descomplicar®-blue)](https://descomplicar.pt)
[![WordPress](https://img.shields.io/badge/Built%20on-WordPress-blue)](https://wordpress.org)
[![KiviCare](https://img.shields.io/badge/Integrated%20with-KiviCare-green)](https://wordpress.org/plugins/kivicare-clinic-management-system/)

*Simplifying healthcare technology, one API at a time.* ✨

</div>