backend-service/docs/API.md
ats-tech25 04f2d02afc docs(api comprehensive API documentation for attune Heart Therapy
Add detailed API:
- Complete API documentation for In Format Usage flow diagrams for authentication and booking processes
- Comprehensive endpoint descriptions with request/response examples
- Detailed authentication and booking flow explanations
- Structured documentation for health checks, authentication, and booking endpoints
-: - Includes JWT authentication details
usage
- Provides clear API usage patterns for users and clients and administrators
system interactions
- Enhances project documentation with provides clear, structured API reference
- Improves developer and user understanding of system capabilities
2025-11-07 19:22:46 +00:00

647 lines
14 KiB
Markdown

# Attune Heart Therapy API Documentation
## Overview
The Attune Heart Therapy API is a comprehensive video conference booking system that enables users to schedule therapy sessions, process payments, and manage appointments. The API provides endpoints for user authentication, booking management, payment processing, and administrative functions.
**Base URL:** `http://localhost:8080`
**API Version:** v1
**Authentication:** JWT Bearer Token
## Table of Contents
1. [Authentication Flow](#authentication-flow)
2. [API Usage Flow](#api-usage-flow)
3. [Endpoints](#endpoints)
4. [Data Models](#data-models)
5. [Error Handling](#error-handling)
6. [Rate Limiting](#rate-limiting)
## Authentication Flow
The API uses JWT (JSON Web Token) for authentication. Here's the authentication flow:
1. **Register** a new user account or **Login** with existing credentials
2. Receive a JWT token in the response
3. Include the token in the `Authorization` header for protected endpoints: `Bearer <token>`
4. Token expires after 24 hours (configurable)
### Authentication Headers
```
Authorization: Bearer <jwt_token>
Content-Type: application/json
```
## API Usage Flow
### For Regular Users (Clients)
```mermaid
graph TD
A[Register/Login] --> B[Get Available Slots]
B --> C[Create Booking]
C --> D[Create Payment Intent]
D --> E[Confirm Payment]
E --> F[Receive Jitsi Room Details]
F --> G[Join Video Session]
C --> H[View My Bookings]
H --> I[Cancel/Reschedule Booking]
```
### For Administrators
```mermaid
graph TD
A[Admin Login] --> B[View Dashboard]
B --> C[Create Schedule Slots]
C --> D[Manage Users]
D --> E[View All Bookings]
E --> F[Generate Reports]
```
### Typical User Journey
1. **User Registration/Login**
- New users register with personal details
- Existing users login with email/password
- System returns JWT token for subsequent requests
2. **Browse Available Slots**
- User queries available time slots for specific dates
- System returns available schedule slots
3. **Create Booking**
- User selects a time slot and creates a booking
- System reserves the slot and returns booking details
4. **Payment Processing**
- User initiates payment through Stripe integration
- System creates payment intent and processes payment
- Upon successful payment, booking is confirmed
5. **Session Management**
- System generates Jitsi room details
- User receives video conference link
- User can view, cancel, or reschedule bookings
## Endpoints
### Health & Monitoring
#### GET /health
Basic health check endpoint.
**Response:**
```json
{
"status": "ok",
"message": "Video Conference Booking System API",
"timestamp": "2024-12-06T10:00:00Z"
}
```
#### GET /health/detailed
Detailed system health check.
**Response:**
```json
{
"status": "healthy",
"checks": {
"database": "healthy",
"job_manager": "healthy",
"memory": "healthy"
},
"timestamp": "2024-12-06T10:00:00Z"
}
```
#### GET /metrics
System metrics and monitoring data.
### Authentication Endpoints
#### POST /api/auth/register
Register a new user account.
**Request Body:**
```json
{
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"location": "New York, NY",
"password": "securepassword123"
}
```
**Response (201):**
```json
{
"message": "User registered successfully",
"user": {
"id": 1,
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"location": "New York, NY",
"is_admin": false,
"created_at": "2024-12-06T10:00:00Z"
}
}
```
#### POST /api/auth/login
Authenticate user and receive JWT token.
**Request Body:**
```json
{
"email": "john.doe@example.com",
"password": "securepassword123"
}
```
**Response (200):**
```json
{
"message": "Login successful",
"user": {
"id": 1,
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"is_admin": false
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
#### GET /api/auth/profile
Get current user profile (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Response (200):**
```json
{
"user": {
"id": 1,
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"location": "New York, NY",
"is_admin": false
}
}
```
#### PUT /api/auth/profile
Update user profile (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"first_name": "John",
"last_name": "Smith",
"phone": "+1234567891",
"location": "Los Angeles, CA"
}
```
#### POST /api/auth/logout
Logout user (requires authentication).
**Headers:** `Authorization: Bearer <token>`
### Schedule & Booking Endpoints
#### GET /api/schedules
Get available time slots for a specific date.
**Query Parameters:**
- `date` (required): Date in YYYY-MM-DD format
**Example:** `/api/schedules?date=2024-12-15`
**Response (200):**
```json
{
"date": "2024-12-15",
"slots": [
{
"id": 1,
"start_time": "2024-12-15T10:00:00Z",
"end_time": "2024-12-15T11:00:00Z",
"is_available": true,
"max_bookings": 1,
"booked_count": 0,
"remaining_slots": 1
}
]
}
```
#### POST /api/bookings
Create a new booking (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"schedule_id": 1,
"duration": 60,
"notes": "Initial consultation session"
}
```
**Response (201):**
```json
{
"message": "Booking created successfully",
"booking": {
"id": 1,
"user_id": 1,
"scheduled_at": "2024-12-15T10:00:00Z",
"duration": 60,
"status": "scheduled",
"jitsi_room_id": "room_abc123",
"jitsi_room_url": "https://meet.jit.si/room_abc123",
"amount": 100.00,
"payment_status": "pending",
"notes": "Initial consultation session"
}
}
```
#### GET /api/bookings
Get all bookings for the current user (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Response (200):**
```json
{
"bookings": [
{
"id": 1,
"scheduled_at": "2024-12-15T10:00:00Z",
"duration": 60,
"status": "scheduled",
"jitsi_room_url": "https://meet.jit.si/room_abc123",
"amount": 100.00,
"payment_status": "succeeded"
}
]
}
```
#### PUT /api/bookings/:id/cancel
Cancel a booking (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Requirements:** Booking must be at least 24 hours before scheduled time.
**Response (200):**
```json
{
"message": "Booking cancelled successfully"
}
```
#### PUT /api/bookings/:id/reschedule
Reschedule a booking to a new time slot (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"new_schedule_id": 2
}
```
**Requirements:** Booking must be at least 2 hours before scheduled time.
### Payment Endpoints
#### POST /api/payments/intent
Create a payment intent for Stripe (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"amount": 10000,
"currency": "usd"
}
```
**Note:** Amount is in cents (10000 = $100.00)
**Response (201):**
```json
{
"message": "Payment intent created successfully",
"client_secret": "pi_1234567890_secret_abc123",
"payment_intent": "pi_1234567890",
"amount": 10000,
"currency": "usd",
"status": "requires_payment_method"
}
```
#### POST /api/payments/confirm
Confirm a payment intent (requires authentication).
**Headers:** `Authorization: Bearer <token>`
**Request Body:**
```json
{
"payment_intent_id": "pi_1234567890"
}
```
**Response (200):**
```json
{
"message": "Payment confirmed successfully",
"payment_intent": "pi_1234567890",
"status": "succeeded",
"amount": 10000,
"currency": "usd"
}
```
#### POST /api/payments/webhook
Stripe webhook endpoint (no authentication required).
**Headers:**
- `Content-Type: application/json`
- `Stripe-Signature: <stripe_signature>`
### Admin Endpoints
All admin endpoints require authentication with admin privileges.
#### GET /api/admin/dashboard
Get dashboard statistics (admin only).
**Headers:** `Authorization: Bearer <admin_token>`
**Response (200):**
```json
{
"stats": {
"total_users": 150,
"total_bookings": 89,
"pending_bookings": 12,
"completed_bookings": 67,
"cancelled_bookings": 10,
"total_revenue": 8900.00,
"monthly_revenue": 2100.00
}
}
```
#### POST /api/admin/schedules
Create a new schedule slot (admin only).
**Headers:** `Authorization: Bearer <admin_token>`
**Request Body:**
```json
{
"start_time": "2024-12-15T10:00:00Z",
"end_time": "2024-12-15T11:00:00Z",
"max_bookings": 1,
"is_available": true
}
```
#### PUT /api/admin/schedules/:id
Update an existing schedule slot (admin only).
#### GET /api/admin/users
Get all users with pagination (admin only).
**Query Parameters:**
- `limit` (optional): Number of users to return (default: 50)
- `offset` (optional): Number of users to skip (default: 0)
#### GET /api/admin/bookings
Get all bookings with pagination (admin only).
#### GET /api/admin/reports/financial
Get financial reports for a date range (admin only).
**Query Parameters:**
- `start_date` (required): Start date in YYYY-MM-DD format
- `end_date` (required): End date in YYYY-MM-DD format
## Data Models
### User
```json
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"email": "john.doe@example.com",
"phone": "+1234567890",
"location": "New York, NY",
"date_of_birth": "1990-01-01T00:00:00Z",
"is_admin": false,
"created_at": "2024-12-06T10:00:00Z",
"updated_at": "2024-12-06T10:00:00Z"
}
```
### Booking
```json
{
"id": 1,
"user_id": 1,
"scheduled_at": "2024-12-15T10:00:00Z",
"duration": 60,
"status": "scheduled",
"jitsi_room_id": "room_abc123",
"jitsi_room_url": "https://meet.jit.si/room_abc123",
"payment_id": "pi_1234567890",
"payment_status": "succeeded",
"amount": 100.00,
"notes": "Initial consultation session",
"created_at": "2024-12-06T10:00:00Z",
"updated_at": "2024-12-06T10:00:00Z"
}
```
### Schedule
```json
{
"id": 1,
"start_time": "2024-12-15T10:00:00Z",
"end_time": "2024-12-15T11:00:00Z",
"is_available": true,
"max_bookings": 1,
"booked_count": 0,
"created_at": "2024-12-06T10:00:00Z",
"updated_at": "2024-12-06T10:00:00Z"
}
```
## Status Codes
### Booking Status
- `scheduled`: Booking is confirmed and scheduled
- `completed`: Session has been completed
- `cancelled`: Booking has been cancelled
### Payment Status
- `pending`: Payment is pending
- `succeeded`: Payment was successful
- `failed`: Payment failed
- `refunded`: Payment was refunded
## Error Handling
The API returns standard HTTP status codes and error messages in JSON format.
### Error Response Format
```json
{
"error": "Error message",
"details": "Detailed error information"
}
```
### Common HTTP Status Codes
- `200 OK`: Request successful
- `201 Created`: Resource created successfully
- `400 Bad Request`: Invalid request format or parameters
- `401 Unauthorized`: Authentication required or invalid token
- `403 Forbidden`: Insufficient permissions
- `404 Not Found`: Resource not found
- `409 Conflict`: Resource conflict (e.g., time slot already booked)
- `422 Payment Required`: Payment failed or required
- `500 Internal Server Error`: Server error
### Common Error Scenarios
#### Authentication Errors
```json
{
"error": "User not authenticated"
}
```
#### Validation Errors
```json
{
"error": "Invalid request format",
"details": "Email is required"
}
```
#### Business Logic Errors
```json
{
"error": "The selected time slot is no longer available"
}
```
## Rate Limiting
The API implements rate limiting to prevent abuse:
- **General endpoints**: 100 requests per minute per IP
- **Authentication endpoints**: 5 requests per minute per IP (strict rate limiting)
- **Admin endpoints**: 200 requests per minute per authenticated admin
Rate limit headers are included in responses:
- `X-RateLimit-Limit`: Request limit per window
- `X-RateLimit-Remaining`: Remaining requests in current window
- `X-RateLimit-Reset`: Time when the rate limit resets
## Security Features
- **JWT Authentication**: Secure token-based authentication
- **Password Hashing**: Bcrypt hashing for user passwords
- **CORS Protection**: Cross-origin request protection
- **Rate Limiting**: Protection against abuse and DDoS
- **Input Validation**: Comprehensive request validation
- **SQL Injection Protection**: Parameterized queries with GORM
- **Security Headers**: Standard security headers included
## Integration Examples
### Frontend Integration (JavaScript)
```javascript
// Login and store token
const loginResponse = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com',
password: 'password123'
})
});
const { token } = await loginResponse.json();
localStorage.setItem('authToken', token);
// Make authenticated request
const bookingsResponse = await fetch('/api/bookings', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('authToken')}`
}
});
```
### cURL Examples
```bash
# Register user
curl -X POST http://localhost:8080/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"first_name": "John",
"last_name": "Doe",
"email": "john@example.com",
"password": "password123"
}'
# Login
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "john@example.com",
"password": "password123"
}'
# Get available slots
curl -X GET "http://localhost:8080/api/schedules?date=2024-12-15"
# Create booking (with auth token)
curl -X POST http://localhost:8080/api/bookings \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"schedule_id": 1,
"duration": 60,
"notes": "Initial consultation"
}'
```
## Support
For API support and questions, please contact the development team or refer to the project documentation.