# 📚 EasyStream REST API Documentation

## 🎯 **Complete Guide to Using the EasyStream API**

The EasyStream API is a comprehensive RESTful API that allows you to integrate with the EasyStream video platform. This API enables mobile app development, third-party integrations, content syndication, and automation.

---

## 🚀 **Getting Started**

### **Base URL**
```
https://yourdomain.com/api/v1/
```

### **Content Type**
All requests and responses use JSON format:
```
Content-Type: application/json
```

### **CORS Support**
The API supports Cross-Origin Resource Sharing (CORS) for web applications.

---

## 🔐 **Authentication**

### **1. JWT Bearer Token (Recommended)**

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

**Response:**
```json
{
  "status": 200,
  "data": {
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
    "user": {
      "id": 123,
      "username": "your_username",
      "email": "user@example.com",
      "display_name": "Your Name"
    },
    "expires_in": 86400
  },
  "timestamp": 1642518000,
  "version": "v1"
}
```

**Step 2: Use token in subsequent requests**
```bash
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
```

### **2. API Key Authentication**

**Generate API Key** (via admin panel or user settings)
```bash
curl -H "Authorization: ApiKey your_api_key_here"
```

---

## 📊 **Rate Limiting**

| Endpoint Type | Limit | Window |
|---------------|-------|--------|
| Authentication | 10 requests | 5 minutes |
| Upload | 5 requests | 1 hour |
| Default | 100 requests | 1 hour |

**Rate limit headers in response:**
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1642521600
```

---

## 🎬 **Video Endpoints**

### **Get Videos**
```bash
GET /api/v1/videos
```

**Parameters:**
- `page` (int): Page number (default: 1)
- `limit` (int): Items per page (max: 50, default: 20)
- `category` (string): Filter by category
- `sort` (string): Sort order (`recent`, `popular`, `rating`)
- `search` (string): Search query

**Example:**
```bash
curl -X GET "https://yourdomain.com/api/v1/videos?limit=10&category=gaming&sort=popular" \
  -H "Authorization: Bearer your_token"
```

**Response:**
```json
{
  "status": 200,
  "data": {
    "videos": [
      {
        "id": "video_123",
        "title": "Epic Gaming Moments",
        "description": "Amazing highlights from today's stream",
        "views": 1250,
        "rating": 4.8,
        "duration": 300,
        "size": 52428800,
        "uploaded_at": "2025-01-18 10:30:00",
        "uploader": {
          "username": "gamer_pro",
          "display_name": "Pro Gamer"
        },
        "thumbnail_url": "/thumbnails/video_123_medium.jpg",
        "video_url": "/watch/video_123"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 150
    }
  }
}
```

### **Get Single Video**
```bash
GET /api/v1/videos/{video_id}
```

**Example:**
```bash
curl -X GET "https://yourdomain.com/api/v1/videos/video_123" \
  -H "Authorization: Bearer your_token"
```

**Response:**
```json
{
  "status": 200,
  "data": {
    "id": "video_123",
    "title": "Epic Gaming Moments",
    "description": "Amazing highlights from today's stream",
    "full_description": "Full detailed description with timestamps...",
    "views": 1250,
    "rating": 4.8,
    "duration": 300,
    "size": 52428800,
    "category": "gaming",
    "tags": ["gaming", "highlights", "stream"],
    "privacy": "public",
    "uploaded_at": "2025-01-18 10:30:00",
    "uploader": {
      "id": 456,
      "username": "gamer_pro",
      "display_name": "Pro Gamer"
    },
    "thumbnail_urls": {
      "small": "/thumbnails/video_123_small.jpg",
      "medium": "/thumbnails/video_123_medium.jpg",
      "large": "/thumbnails/video_123_large.jpg"
    },
    "video_files": {
      "1080p": "/videos/video_123_1080p.mp4",
      "720p": "/videos/video_123_720p.mp4",
      "480p": "/videos/video_123_480p.mp4"
    },
    "hls_url": "/hls/video_123/master.m3u8"
  }
}
```

### **Upload Video**
```bash
POST /api/v1/videos
```

**Multipart form data:**
```bash
curl -X POST "https://yourdomain.com/api/v1/videos" \
  -H "Authorization: Bearer your_token" \
  -F "video=@video.mp4" \
  -F "title=My Amazing Video" \
  -F "description=This is my video description" \
  -F "category=entertainment" \
  -F "tags=fun,awesome,video" \
  -F "privacy=public"
```

**Response:**
```json
{
  "status": 201,
  "data": {
    "id": "video_456",
    "title": "My Amazing Video",
    "status": "processing",
    "upload_progress": 100,
    "processing_status": "queued"
  }
}
```

### **Update Video**
```bash
PUT /api/v1/videos/{video_id}
```

**Example:**
```bash
curl -X PUT "https://yourdomain.com/api/v1/videos/video_123" \
  -H "Authorization: Bearer your_token" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Updated Video Title",
    "description": "Updated description",
    "privacy": "unlisted"
  }'
```

### **Delete Video**
```bash
DELETE /api/v1/videos/{video_id}
```

### **Like Video**
```bash
POST /api/v1/videos/{video_id}/like
```

### **Comment on Video**
```bash
POST /api/v1/videos/{video_id}/comment
```

**Body:**
```json
{
  "comment": "Great video! Love the content."
}
```

### **Get Video Comments**
```bash
GET /api/v1/videos/{video_id}/comments?page=1&limit=20
```

---

## 👤 **User Endpoints**

### **Get Users**
```bash
GET /api/v1/users?page=1&limit=20&search=username
```

### **Get User Profile**
```bash
GET /api/v1/users/{user_id}
```

**Response:**
```json
{
  "status": 200,
  "data": {
    "id": 123,
    "username": "gamer_pro",
    "display_name": "Pro Gamer",
    "email": "gamer@example.com",
    "avatar_url": "/avatars/123.jpg",
    "bio": "Professional gamer and content creator",
    "followers_count": 1250,
    "following_count": 89,
    "videos_count": 45,
    "total_views": 125000,
    "joined_at": "2024-01-15 09:30:00",
    "is_verified": true,
    "social_links": {
      "twitter": "https://twitter.com/gamer_pro",
      "youtube": "https://youtube.com/c/gamerpro"
    }
  }
}
```

### **Update Profile**
```bash
PUT /api/v1/users/me
```

**Body:**
```json
{
  "display_name": "New Display Name",
  "bio": "Updated bio",
  "social_links": {
    "twitter": "https://twitter.com/newhandle"
  }
}
```

### **Follow User**
```bash
POST /api/v1/users/{user_id}/follow
```

### **Unfollow User**
```bash
DELETE /api/v1/users/{user_id}/follow
```

### **Get User's Videos**
```bash
GET /api/v1/users/{user_id}/videos?page=1&limit=20
```

### **Get User's Followers**
```bash
GET /api/v1/users/{user_id}/followers?page=1&limit=20
```

### **Get User's Following**
```bash
GET /api/v1/users/{user_id}/following?page=1&limit=20
```

---

## 🎥 **Live Streaming Endpoints**

### **Get Live Streams**
```bash
GET /api/v1/live?category=gaming&status=live
```

**Response:**
```json
{
  "status": 200,
  "data": {
    "streams": [
      {
        "id": 789,
        "title": "Live Gaming Session",
        "description": "Playing the latest games",
        "category": "gaming",
        "status": "live",
        "viewer_count": 45,
        "started_at": "2025-01-18 14:30:00",
        "streamer": {
          "username": "live_gamer",
          "display_name": "Live Gamer"
        },
        "thumbnail_url": "/live/thumbnails/789.jpg",
        "hls_url": "https://yourdomain.com/live/hls/stream_789.m3u8"
      }
    ]
  }
}
```

### **Create Live Stream**
```bash
POST /api/v1/live
```

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

**Response:**
```json
{
  "status": 201,
  "data": {
    "stream_id": 789,
    "stream_key": "stream_123_abc456_1642518000",
    "rtmp_url": "rtmp://yourdomain.com:1935/live",
    "stream_url": "rtmp://yourdomain.com:1935/live/stream_123_abc456_1642518000",
    "hls_url": "https://yourdomain.com/live/hls/stream_123_abc456_1642518000.m3u8",
    "dashboard_url": "/live/dashboard/789"
  }
}
```

### **Get Stream Details**
```bash
GET /api/v1/live/{stream_id}
```

### **Start Stream**
```bash
POST /api/v1/live/{stream_id}/start
```

### **Stop Stream**
```bash
POST /api/v1/live/{stream_id}/stop
```

### **Update Stream**
```bash
PUT /api/v1/live/{stream_id}
```

---

## 🔍 **Search Endpoint**

### **Search Content**
```bash
GET /api/v1/search?q=gaming&type=videos&limit=20
```

**Parameters:**
- `q` (string): Search query
- `type` (string): Content type (`videos`, `users`, `channels`, `all`)
- `category` (string): Filter by category
- `sort` (string): Sort order (`relevance`, `recent`, `popular`)

**Response:**
```json
{
  "status": 200,
  "data": {
    "query": "gaming",
    "results": {
      "videos": [...],
      "users": [...],
      "total_results": 150
    },
    "suggestions": ["gaming highlights", "gaming tutorial", "gaming review"]
  }
}
```

---

## 📊 **Analytics Endpoints**

### **Get Platform Overview**
```bash
GET /api/v1/analytics/overview?start_date=2025-01-01&end_date=2025-01-31
```

**Response:**
```json
{
  "status": 200,
  "data": {
    "users": {
      "total_users": 10000,
      "active_users": 2500,
      "new_users": 150
    },
    "content": {
      "total_videos": 5000,
      "new_videos": 45,
      "total_views": 1000000
    },
    "engagement": {
      "total_likes": 50000,
      "total_comments": 25000,
      "total_shares": 5000
    },
    "streaming": {
      "total_streams": 500,
      "live_streams": 12,
      "total_viewers": 1500
    }
  }
}
```

### **Get Video Analytics**
```bash
GET /api/v1/analytics/videos/{video_id}?period=30d
```

### **Get User Analytics**
```bash
GET /api/v1/analytics/users/{user_id}?period=7d
```

### **Generate Report**
```bash
POST /api/v1/analytics/reports
```

**Body:**
```json
{
  "report_type": "user_growth",
  "parameters": {
    "start_date": "2025-01-01",
    "end_date": "2025-01-31",
    "format": "json"
  }
}
```

---

## 🔧 **Error Handling**

### **HTTP Status Codes**
- `200` - Success
- `201` - Created
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `405` - Method Not Allowed
- `429` - Rate Limited
- `500` - Internal Server Error

### **Error Response Format**
```json
{
  "status": 400,
  "data": {
    "error": "Invalid request parameters",
    "details": {
      "field": "title",
      "message": "Title is required"
    }
  },
  "timestamp": 1642518000,
  "version": "v1"
}
```

---

## 💻 **Code Examples**

### **JavaScript/Node.js**
```javascript
// Login and get token
const login = async (username, password) => {
  const response = await fetch('https://yourdomain.com/api/v1/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });
  
  const data = await response.json();
  return data.data.token;
};

// Get videos
const getVideos = async (token, limit = 20) => {
  const response = await fetch(`https://yourdomain.com/api/v1/videos?limit=${limit}`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  const data = await response.json();
  return data.data.videos;
};

// Upload video
const uploadVideo = async (token, videoFile, title, description) => {
  const formData = new FormData();
  formData.append('video', videoFile);
  formData.append('title', title);
  formData.append('description', description);
  
  const response = await fetch('https://yourdomain.com/api/v1/videos', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${token}` },
    body: formData
  });
  
  return await response.json();
};
```

### **Python**
```python
import requests

class EasyStreamAPI:
    def __init__(self, base_url):
        self.base_url = base_url.rstrip('/')
        self.token = None
    
    def login(self, username, password):
        response = requests.post(f'{self.base_url}/api/v1/auth/login', json={
            'username': username,
            'password': password
        })
        
        if response.status_code == 200:
            self.token = response.json()['data']['token']
            return True
        return False
    
    def get_videos(self, limit=20, category=None):
        headers = {'Authorization': f'Bearer {self.token}'}
        params = {'limit': limit}
        if category:
            params['category'] = category
        
        response = requests.get(f'{self.base_url}/api/v1/videos', 
                              headers=headers, params=params)
        
        if response.status_code == 200:
            return response.json()['data']['videos']
        return []
    
    def upload_video(self, video_path, title, description):
        headers = {'Authorization': f'Bearer {self.token}'}
        
        with open(video_path, 'rb') as video_file:
            files = {'video': video_file}
            data = {'title': title, 'description': description}
            
            response = requests.post(f'{self.base_url}/api/v1/videos',
                                   headers=headers, files=files, data=data)
        
        return response.json()

# Usage
api = EasyStreamAPI('https://yourdomain.com')
api.login('username', 'password')
videos = api.get_videos(limit=10, category='gaming')
```

### **PHP**
```php
class EasyStreamAPI {
    private $baseUrl;
    private $token;
    
    public function __construct($baseUrl) {
        $this->baseUrl = rtrim($baseUrl, '/');
    }
    
    public function login($username, $password) {
        $data = json_encode(['username' => $username, 'password' => $password]);
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->baseUrl . '/api/v1/auth/login',
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        if ($result['status'] === 200) {
            $this->token = $result['data']['token'];
            return true;
        }
        
        return false;
    }
    
    public function getVideos($limit = 20, $category = null) {
        $url = $this->baseUrl . '/api/v1/videos?limit=' . $limit;
        if ($category) {
            $url .= '&category=' . urlencode($category);
        }
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $this->token],
            CURLOPT_RETURNTRANSFER => true
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        return $result['status'] === 200 ? $result['data']['videos'] : [];
    }
}

// Usage
$api = new EasyStreamAPI('https://yourdomain.com');
$api->login('username', 'password');
$videos = $api->getVideos(10, 'gaming');
```

---

## 🔄 **Content Syndication Use Cases**

### **1. Cross-Platform Posting**
Extract video metadata and post to YouTube, TikTok, Twitter, Facebook:

```python
# Get video data
videos = api.get_videos(limit=10, category='gaming')

for video in videos:
    # Extract metadata
    title = video['title']
    description = video['description']
    tags = video.get('tags', [])
    
    # Post to YouTube
    youtube_api.upload_video(title, description, tags)
    
    # Post to Twitter
    tweet = f"🎥 {title[:100]}... Watch: {video['video_url']}"
    twitter_api.post_tweet(tweet)
    
    # Post to Facebook
    facebook_api.post_video_link(title, description, video['video_url'])
```

### **2. Content Aggregation**
Build content aggregation services:

```javascript
// Aggregate content from multiple EasyStream instances
const instances = [
  'https://gaming.example.com',
  'https://music.example.com',
  'https://education.example.com'
];

const aggregatedContent = [];

for (const instance of instances) {
  const api = new EasyStreamAPI(instance);
  const videos = await api.getVideos(20);
  aggregatedContent.push(...videos);
}

// Sort by popularity and recency
aggregatedContent.sort((a, b) => b.views - a.views);
```

### **3. Analytics Dashboard**
Build external analytics dashboards:

```python
# Collect analytics from multiple channels
analytics_data = []

for user_id in user_ids:
    user_analytics = api.get_user_analytics(user_id, period='30d')
    analytics_data.append(user_analytics)

# Generate reports
generate_performance_report(analytics_data)
send_weekly_summary_email(analytics_data)
```

---

## 🛠️ **SDK and Tools**

### **Official SDKs** (Coming Soon)
- JavaScript/TypeScript SDK
- Python SDK
- PHP SDK
- Mobile SDKs (iOS/Android)

### **Postman Collection**
Import the EasyStream API collection for easy testing:
```
https://yourdomain.com/api/v1/postman-collection.json
```

### **OpenAPI Specification**
Full API specification available at:
```
https://yourdomain.com/api/v1/openapi.json
```

---

## 🔒 **Security Best Practices**

### **1. Token Management**
- Store JWT tokens securely
- Refresh tokens before expiration
- Never expose tokens in client-side code

### **2. Rate Limiting**
- Implement client-side rate limiting
- Handle 429 responses gracefully
- Use exponential backoff for retries

### **3. Input Validation**
- Validate all input data
- Sanitize user-generated content
- Use HTTPS for all requests

### **4. Error Handling**
- Handle all HTTP status codes
- Implement proper error logging
- Provide user-friendly error messages

---

## 📞 **Support and Resources**

### **API Status**
Check API status and uptime:
```
https://yourdomain.com/api/v1/status
```

### **Rate Limit Status**
Check your current rate limit status:
```
https://yourdomain.com/api/v1/rate-limit-status
```

### **Documentation Updates**
This documentation is updated regularly. Check the version and last updated date:
```json
{
  "version": "v1",
  "last_updated": "2025-01-18",
  "documentation_version": "1.0.0"
}
```

---

## 🎉 **Conclusion**

The EasyStream API provides comprehensive access to all platform features, enabling you to:

✅ **Build mobile applications** with full video platform functionality
✅ **Create content syndication tools** for cross-platform posting
✅ **Develop analytics dashboards** with real-time metrics
✅ **Integrate live streaming** into your applications
✅ **Automate content management** workflows
✅ **Build third-party integrations** and tools

**The API is production-ready and designed for scalability, security, and ease of use.**

For additional support, examples, or feature requests, please refer to the platform documentation or contact the development team.

**🚀 Start building amazing applications with the EasyStream API today!**