# API Documentation

EasyStream provides a comprehensive REST API for integrating with external applications and building custom clients.

## Base URL
```
https://your-domain.com/api/
```

## Authentication

### API Key Authentication
Include your API key in the request headers:
```http
Authorization: Bearer YOUR_API_KEY
X-API-Key: YOUR_API_KEY
```

### Session Authentication
For web applications, use session-based authentication:
```http
Cookie: PHPSESSID=your_session_id
```

### Rate Limiting
- **Default**: 1000 requests per hour per API key
- **Authenticated users**: 5000 requests per hour
- **Premium users**: 10000 requests per hour

Rate limit headers are included in responses:
```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1640995200
```

## Response Format

### Success Response
```json
{
    "success": true,
    "data": {
        // Response data
    },
    "meta": {
        "timestamp": "2024-01-01T12:00:00Z",
        "version": "1.0"
    }
}
```

### Error Response
```json
{
    "success": false,
    "error": {
        "code": "VALIDATION_ERROR",
        "message": "Invalid input parameters",
        "details": {
            "field": "email",
            "issue": "Invalid email format"
        }
    },
    "meta": {
        "timestamp": "2024-01-01T12:00:00Z",
        "version": "1.0"
    }
}
```

## Authentication Endpoints

### POST /api/auth/login
Authenticate user and create session.

**Request:**
```json
{
    "username": "user@example.com",
    "password": "password123",
    "remember": true
}
```

**Response:**
```json
{
    "success": true,
    "data": {
        "user": {
            "id": 123,
            "username": "user@example.com",
            "role": "user",
            "permissions": ["video.upload", "video.view"]
        },
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
        "expires_at": "2024-01-02T12:00:00Z"
    }
}
```

### POST /api/auth/logout
Logout user and invalidate session.

**Response:**
```json
{
    "success": true,
    "data": {
        "message": "Successfully logged out"
    }
}
```

### GET /api/auth/me
Get current user information.

**Response:**
```json
{
    "success": true,
    "data": {
        "user": {
            "id": 123,
            "username": "user@example.com",
            "email": "user@example.com",
            "role": "user",
            "created_at": "2024-01-01T00:00:00Z",
            "last_login": "2024-01-01T12:00:00Z"
        }
    }
}
```

## Video Management

### GET /api/videos
List videos with pagination and filtering.

**Parameters:**
- `page` (int): Page number (default: 1)
- `limit` (int): Items per page (default: 20, max: 100)
- `category` (string): Filter by category
- `user_id` (int): Filter by user
- `status` (string): Filter by status (published, processing, draft)
- `sort` (string): Sort by (created_at, views, likes, title)
- `order` (string): Sort order (asc, desc)

**Response:**
```json
{
    "success": true,
    "data": {
        "videos": [
            {
                "id": 456,
                "title": "Sample Video",
                "description": "Video description",
                "thumbnail": "https://example.com/thumb.jpg",
                "duration": 120,
                "views": 1000,
                "likes": 50,
                "status": "published",
                "created_at": "2024-01-01T10:00:00Z",
                "user": {
                    "id": 123,
                    "username": "creator"
                }
            }
        ],
        "pagination": {
            "current_page": 1,
            "total_pages": 10,
            "total_items": 200,
            "items_per_page": 20
        }
    }
}
```

### GET /api/videos/{id}
Get specific video details.

**Response:**
```json
{
    "success": true,
    "data": {
        "video": {
            "id": 456,
            "title": "Sample Video",
            "description": "Detailed video description",
            "thumbnail": "https://example.com/thumb.jpg",
            "video_url": "https://example.com/video.mp4",
            "hls_url": "https://example.com/hls/video/playlist.m3u8",
            "duration": 120,
            "views": 1000,
            "likes": 50,
            "dislikes": 5,
            "status": "published",
            "category": "entertainment",
            "tags": ["funny", "viral"],
            "created_at": "2024-01-01T10:00:00Z",
            "updated_at": "2024-01-01T11:00:00Z",
            "user": {
                "id": 123,
                "username": "creator",
                "avatar": "https://example.com/avatar.jpg"
            }
        }
    }
}
```

### POST /api/videos
Upload a new video.

**Request (multipart/form-data):**
```
title: "My Video Title"
description: "Video description"
category: "entertainment"
tags: "funny,viral"
privacy: "public"
file: [video file]
thumbnail: [image file] (optional)
```

**Response:**
```json
{
    "success": true,
    "data": {
        "video": {
            "id": 789,
            "title": "My Video Title",
            "status": "processing",
            "upload_progress": 100,
            "processing_progress": 0,
            "created_at": "2024-01-01T12:00:00Z"
        }
    }
}
```

### PUT /api/videos/{id}
Update video information.

**Request:**
```json
{
    "title": "Updated Title",
    "description": "Updated description",
    "category": "education",
    "tags": ["tutorial", "howto"],
    "privacy": "unlisted"
}
```

### DELETE /api/videos/{id}
Delete a video.

**Response:**
```json
{
    "success": true,
    "data": {
        "message": "Video deleted successfully"
    }
}
```

### GET /api/videos/{id}/progress
Get video processing progress.

**Response:**
```json
{
    "success": true,
    "data": {
        "video_id": 789,
        "status": "processing",
        "progress": {
            "upload": 100,
            "processing": 45,
            "thumbnail": 100,
            "hls": 30
        },
        "estimated_completion": "2024-01-01T12:15:00Z"
    }
}
```

## Live Streaming

### GET /api/streams
List live streams.

**Response:**
```json
{
    "success": true,
    "data": {
        "streams": [
            {
                "id": 101,
                "title": "Live Gaming Session",
                "description": "Playing the latest game",
                "thumbnail": "https://example.com/stream_thumb.jpg",
                "status": "live",
                "viewers": 150,
                "started_at": "2024-01-01T12:00:00Z",
                "stream_key": "abc123def456",
                "rtmp_url": "rtmp://example.com/live/abc123def456",
                "hls_url": "https://example.com/hls/live/abc123def456/index.m3u8",
                "user": {
                    "id": 123,
                    "username": "streamer"
                }
            }
        ]
    }
}
```

### POST /api/streams
Create a new live stream.

**Request:**
```json
{
    "title": "My Live Stream",
    "description": "Stream description",
    "category": "gaming",
    "privacy": "public"
}
```

**Response:**
```json
{
    "success": true,
    "data": {
        "stream": {
            "id": 102,
            "title": "My Live Stream",
            "stream_key": "xyz789abc123",
            "rtmp_url": "rtmp://example.com/live/xyz789abc123",
            "hls_url": "https://example.com/hls/live/xyz789abc123/index.m3u8",
            "status": "created",
            "created_at": "2024-01-01T12:00:00Z"
        }
    }
}
```

### PUT /api/streams/{id}/start
Start a live stream.

**Response:**
```json
{
    "success": true,
    "data": {
        "stream": {
            "id": 102,
            "status": "live",
            "started_at": "2024-01-01T12:00:00Z"
        }
    }
}
```

### PUT /api/streams/{id}/stop
Stop a live stream.

**Response:**
```json
{
    "success": true,
    "data": {
        "stream": {
            "id": 102,
            "status": "ended",
            "ended_at": "2024-01-01T13:00:00Z",
            "duration": 3600
        }
    }
}
```

## User Management

### GET /api/users
List users (admin only).

**Parameters:**
- `page` (int): Page number
- `limit` (int): Items per page
- `role` (string): Filter by role
- `status` (string): Filter by status

### GET /api/users/{id}
Get user profile.

**Response:**
```json
{
    "success": true,
    "data": {
        "user": {
            "id": 123,
            "username": "user123",
            "email": "user@example.com",
            "avatar": "https://example.com/avatar.jpg",
            "bio": "User biography",
            "subscriber_count": 1000,
            "video_count": 50,
            "created_at": "2024-01-01T00:00:00Z"
        }
    }
}
```

### PUT /api/users/{id}
Update user profile.

**Request:**
```json
{
    "bio": "Updated biography",
    "avatar": "base64_encoded_image_data"
}
```

## Comments and Interactions

### GET /api/videos/{id}/comments
Get video comments.

**Parameters:**
- `page` (int): Page number
- `limit` (int): Items per page
- `sort` (string): Sort by (created_at, likes)

**Response:**
```json
{
    "success": true,
    "data": {
        "comments": [
            {
                "id": 789,
                "content": "Great video!",
                "likes": 10,
                "replies_count": 2,
                "created_at": "2024-01-01T12:00:00Z",
                "user": {
                    "id": 456,
                    "username": "commenter",
                    "avatar": "https://example.com/avatar.jpg"
                }
            }
        ]
    }
}
```

### POST /api/videos/{id}/comments
Add a comment to a video.

**Request:**
```json
{
    "content": "This is a great video!",
    "parent_id": null
}
```

### POST /api/videos/{id}/like
Like a video.

**Response:**
```json
{
    "success": true,
    "data": {
        "liked": true,
        "like_count": 51
    }
}
```

### DELETE /api/videos/{id}/like
Unlike a video.

**Response:**
```json
{
    "success": true,
    "data": {
        "liked": false,
        "like_count": 50
    }
}
```

## Search

### GET /api/search
Search for videos, users, or streams.

**Parameters:**
- `q` (string): Search query
- `type` (string): Search type (videos, users, streams, all)
- `page` (int): Page number
- `limit` (int): Items per page

**Response:**
```json
{
    "success": true,
    "data": {
        "results": {
            "videos": [...],
            "users": [...],
            "streams": [...]
        },
        "total_results": 150,
        "search_time": 0.05
    }
}
```

## Analytics

### GET /api/analytics/videos/{id}
Get video analytics (owner only).

**Response:**
```json
{
    "success": true,
    "data": {
        "video_id": 456,
        "views": {
            "total": 10000,
            "today": 100,
            "this_week": 500,
            "this_month": 2000
        },
        "engagement": {
            "likes": 500,
            "dislikes": 20,
            "comments": 150,
            "shares": 75
        },
        "demographics": {
            "age_groups": {
                "18-24": 30,
                "25-34": 40,
                "35-44": 20,
                "45+": 10
            },
            "countries": {
                "US": 50,
                "UK": 20,
                "CA": 15,
                "AU": 10,
                "other": 5
            }
        }
    }
}
```

## Webhooks

### Configuration
Configure webhooks in your account settings to receive real-time notifications.

### Events
- `video.uploaded` - New video uploaded
- `video.processed` - Video processing completed
- `stream.started` - Live stream started
- `stream.ended` - Live stream ended
- `comment.created` - New comment added
- `user.subscribed` - New subscriber

### Payload Example
```json
{
    "event": "video.uploaded",
    "timestamp": "2024-01-01T12:00:00Z",
    "data": {
        "video": {
            "id": 789,
            "title": "New Video",
            "user_id": 123
        }
    }
}
```

## Error Codes

### HTTP Status Codes
- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `422` - Validation Error
- `429` - Rate Limit Exceeded
- `500` - Internal Server Error

### Application Error Codes
- `VALIDATION_ERROR` - Input validation failed
- `AUTHENTICATION_REQUIRED` - Authentication required
- `INSUFFICIENT_PERMISSIONS` - Insufficient permissions
- `RESOURCE_NOT_FOUND` - Resource not found
- `RATE_LIMIT_EXCEEDED` - Rate limit exceeded
- `UPLOAD_FAILED` - File upload failed
- `PROCESSING_ERROR` - Video processing error

## SDKs and Libraries

### JavaScript SDK
```javascript
import EasyStreamAPI from 'easystream-api';

const api = new EasyStreamAPI({
    baseURL: 'https://your-domain.com/api',
    apiKey: 'your-api-key'
});

// Upload video
const video = await api.videos.upload({
    title: 'My Video',
    file: videoFile
});

// Get video details
const videoDetails = await api.videos.get(video.id);
```

### PHP SDK
```php
<?php
use EasyStream\API\Client;

$client = new Client([
    'base_url' => 'https://your-domain.com/api',
    'api_key' => 'your-api-key'
]);

// List videos
$videos = $client->videos()->list([
    'limit' => 10,
    'category' => 'entertainment'
]);

// Create stream
$stream = $client->streams()->create([
    'title' => 'My Live Stream',
    'category' => 'gaming'
]);
```

## Testing

### API Testing
Use the provided test endpoints to verify your integration:

```bash
# Test authentication
curl -X POST https://your-domain.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"test@example.com","password":"password"}'

# Test video listing
curl -X GET https://your-domain.com/api/videos \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### Postman Collection
Import our Postman collection for easy API testing:
```
https://your-domain.com/api/postman-collection.json
```

## Support

For API support and questions:
- Documentation: https://docs.your-domain.com
- Support Email: api-support@your-domain.com
- GitHub Issues: https://github.com/your-org/easystream/issues