# ๐Ÿฅ Care API Documentation **Complete REST API Documentation for KiviCare Healthcare Management System**
[![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)
## ๐Ÿ“‹ 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
| 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**
### ๐Ÿ† 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 ` 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 ---
**๐Ÿฅ 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.* โœจ