← back to Watches

docs/API_COMPLETE_GUIDE.md

1345 lines

# Omega Watch Price History API - Complete Developer Guide

![API Version](https://img.shields.io/badge/API-v2.0.0-blue.svg)
![OpenAPI](https://img.shields.io/badge/OpenAPI-3.0.3-green.svg)
![Status](https://img.shields.io/badge/status-production-brightgreen.svg)
![License](https://img.shields.io/badge/license-MIT-blue.svg)

## Table of Contents

- [Quick Start](#quick-start)
- [Authentication](#authentication)
- [API Reference](#api-reference)
- [SDKs & Client Libraries](#sdks--client-libraries)
- [Code Examples](#code-examples)
- [WebSocket API](#websocket-api)
- [Error Handling](#error-handling)
- [Rate Limiting & Best Practices](#rate-limiting--best-practices)
- [Versioning & Migration](#versioning--migration)
- [Testing with Postman](#testing-with-postman)
- [Common Use Cases](#common-use-cases)
- [Troubleshooting](#troubleshooting)

---

## Quick Start

### Base URL
```
Production: http://45.61.58.125:7600
WebSocket:  ws://45.61.58.125:7600
```

### 30-Second Quick Start

```bash
# 1. Test the API
curl http://45.61.58.125:7600/api/health

# 2. Get all watches
curl http://45.61.58.125:7600/api/watches?limit=5

# 3. Search for specific watches
curl "http://45.61.58.125:7600/api/search?q=moonwatch"

# 4. Get price predictions
curl http://45.61.58.125:7600/api/price-predictions/speedmaster-moonwatch-1969
```

### Interactive Documentation

Try the API live in your browser:
- **Swagger UI**: http://45.61.58.125:7600/api/docs/swagger
- **OpenAPI Spec**: http://45.61.58.125:7600/api/docs/openapi.json

---

## Authentication

### Public Endpoints (No Auth Required)
Most endpoints are publicly accessible:
- `/api/health`
- `/api/watches`
- `/api/search`
- `/api/statistics`
- `/api/collections`
- `/api/price-predictions/:id`
- `/api/export/:format`

### Admin Endpoints (API Key Required)
Admin operations require an API key in the `X-API-Key` header:

```bash
curl -H "X-API-Key: your-api-key" \
  -X POST \
  http://45.61.58.125:7600/api/admin/clear-cache
```

**Admin endpoints:**
- `POST /api/admin/clear-cache` - Clear server cache
- `GET /api/admin/backup` - Create database backup

---

## API Reference

### Health & Monitoring

#### `GET /api/health`
Get detailed system health metrics.

**Response:**
```json
{
  "status": "healthy",
  "timestamp": "2025-11-17T10:30:00.000Z",
  "uptime": 3600.5,
  "memory": {
    "rss": 86118400,
    "heapTotal": 16093184,
    "heapUsed": 13925944
  },
  "cache": {
    "keys": 1,
    "size": 41555
  },
  "database": {
    "watches": 32,
    "collections": 9
  },
  "websocket": {
    "connections": 0
  }
}
```

**Use Cases:**
- Health checks in monitoring systems
- Performance tracking
- Debugging cache issues

---

### Watches

#### `GET /api/watches`
Retrieve all watches with filtering and pagination.

**Query Parameters:**

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| `series` | string | No | Filter by collection | `Speedmaster` |
| `minYear` | integer | No | Min year introduced | `1960` |
| `maxYear` | integer | No | Max year introduced | `2000` |
| `minPrice` | integer | No | Min current price (USD) | `5000` |
| `maxPrice` | integer | No | Max current price (USD) | `50000` |
| `page` | integer | No | Page number (default: 1) | `1` |
| `limit` | integer | No | Items per page (default: 50, max: 100) | `20` |

**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/watches?series=Speedmaster&minYear=1960&maxYear=1970&limit=10"
```

**Example Response:**
```json
{
  "total": 18,
  "page": 1,
  "limit": 10,
  "totalPages": 2,
  "watches": [
    {
      "id": "speedmaster-moonwatch-1969",
      "model": "Speedmaster Professional Moonwatch ST 105.012",
      "series": "Speedmaster",
      "reference": "ST 105.012",
      "yearIntroduced": 1963,
      "description": "The legendary Moon Watch worn during Apollo 11",
      "priceHistory": [
        {
          "year": 1963,
          "price": 95,
          "condition": "new",
          "source": "Original retail price"
        },
        {
          "year": 2025,
          "price": 125000,
          "condition": "vintage",
          "source": "Current market average"
        }
      ],
      "specifications": {
        "caseSize": "42mm",
        "caseMaterial": "Stainless steel",
        "movement": "Calibre 321 (manual-winding)",
        "waterResistance": "50m",
        "crystal": "Hesalite",
        "dialColor": "Black",
        "bezel": "Black aluminum tachymeter"
      }
    }
  ]
}
```

---

#### `GET /api/watches/{id}/history`
Get complete price history for a specific watch.

**Path Parameters:**
- `id` (required): Watch identifier (e.g., `speedmaster-moonwatch-1969`)

**Example Request:**
```bash
curl http://45.61.58.125:7600/api/watches/speedmaster-moonwatch-1969/history
```

**Example Response:**
```json
{
  "watch": {
    "id": "speedmaster-moonwatch-1969",
    "model": "Speedmaster Professional Moonwatch ST 105.012",
    "series": "Speedmaster",
    "reference": "ST 105.012",
    "yearIntroduced": 1963,
    "specifications": {
      "caseSize": "42mm",
      "movement": "Calibre 321 (manual-winding)",
      "caseMaterial": "Stainless steel"
    }
  },
  "priceHistory": [
    {
      "year": 1963,
      "price": 95,
      "condition": "new",
      "source": "Launch price"
    },
    {
      "year": 2025,
      "price": 125000,
      "condition": "vintage",
      "source": "Current market"
    }
  ],
  "views": 1542
}
```

**Use Cases:**
- Display price charts
- Track watch appreciation
- Historical analysis

---

#### `GET /api/watches/trending`
Get most viewed watches.

**Query Parameters:**
- `limit` (optional): Number of results (default: 10, max: 50)

**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/watches/trending?limit=5"
```

**Example Response:**
```json
{
  "trending": [
    {
      "id": "speedmaster-moonwatch-1969",
      "model": "Speedmaster Professional Moonwatch ST 105.012",
      "series": "Speedmaster",
      "views": 1542,
      "priceHistory": [...]
    }
  ],
  "totalViews": 12847
}
```

---

### Search

#### `GET /api/search`
Advanced search with multiple filters.

**Query Parameters:**

| Parameter | Type | Required | Description | Example |
|-----------|------|----------|-------------|---------|
| `q` | string | Yes | Search query | `moonwatch` |
| `series` | string | No | Filter by series | `Speedmaster` |
| `movement` | string | No | Filter by movement type | `automatic` |
| `minPrice` | integer | No | Minimum price | `10000` |
| `maxPrice` | integer | No | Maximum price | `100000` |
| `page` | integer | No | Page number | `1` |
| `limit` | integer | No | Items per page | `20` |

**Example Request:**
```bash
curl "http://45.61.58.125:7600/api/search?q=moonwatch&movement=manual&minPrice=50000&limit=5"
```

**Example Response:**
```json
{
  "query": "moonwatch",
  "total": 8,
  "page": 1,
  "limit": 5,
  "totalPages": 2,
  "results": [
    {
      "id": "speedmaster-moonwatch-1969",
      "model": "Speedmaster Professional Moonwatch ST 105.012",
      "series": "Speedmaster",
      "relevance": 0.95
    }
  ]
}
```

**Search Tips:**
- Searches across model, series, reference, description, movement, and case material
- Case-insensitive
- Partial matches supported

---

### Analytics

#### `GET /api/price-predictions/{id}`
Get AI-generated price predictions for next 3 years using linear regression.

**Path Parameters:**
- `id` (required): Watch identifier

**Example Request:**
```bash
curl http://45.61.58.125:7600/api/price-predictions/speedmaster-moonwatch-1969
```

**Example Response:**
```json
{
  "model": "Speedmaster Professional Moonwatch ST 105.012",
  "currentPrice": 125000,
  "trend": "increasing",
  "averageAnnualChange": 8.5,
  "predictions": [
    {
      "year": 2026,
      "predictedPrice": 135625,
      "confidence": 87
    },
    {
      "year": 2027,
      "predictedPrice": 147103,
      "confidence": 82
    },
    {
      "year": 2028,
      "predictedPrice": 159607,
      "confidence": 76
    }
  ]
}
```

**Understanding Predictions:**
- `trend`: "increasing" or "decreasing"
- `averageAnnualChange`: Percentage change per year
- `confidence`: Score 0-100 (higher = more reliable)
- Requires minimum 3 historical price points

---

#### `GET /api/statistics`
Get comprehensive market statistics.

**Example Request:**
```bash
curl http://45.61.58.125:7600/api/statistics
```

**Example Response:**
```json
{
  "totalWatches": 32,
  "totalSeries": 9,
  "averageAppreciation": 247.85,
  "topPerformers": [
    {
      "id": "speedmaster-moonwatch-1957",
      "model": "Speedmaster Professional CK2915",
      "series": "Speedmaster",
      "appreciation": 210426.32,
      "currentPrice": 200000,
      "yearIntroduced": 1957
    }
  ],
  "lastUpdated": "2025-11-17T10:30:00.000Z",
  "priceRanges": {
    "Under $5,000": 8,
    "$5,000 - $10,000": 12,
    "$10,000 - $25,000": 15,
    "$25,000 - $50,000": 10,
    "Over $50,000": 7
  },
  "movementTypes": {
    "Automatic": 35,
    "Manual": 15,
    "Other": 2
  },
  "appreciationByDecade": {
    "1940s": 312.45,
    "1950s": 285.67,
    "1960s": 268.91,
    "1970s": 198.34
  }
}
```

**Use Cases:**
- Market overview dashboards
- Investment analysis
- Trend identification

---

### Collections

#### `GET /api/collections`
Get all watch collections with statistics.

**Example Request:**
```bash
curl http://45.61.58.125:7600/api/collections
```

**Example Response:**
```json
{
  "collections": [
    {
      "series": "Speedmaster",
      "count": 18,
      "avgPrice": 45234,
      "avgAppreciation": 312.45,
      "avgYearIntroduced": 1969,
      "watches": [
        {
          "id": "speedmaster-moonwatch-1969",
          "model": "Speedmaster Professional Moonwatch",
          "reference": "ST 105.012",
          "yearIntroduced": 1963
        }
      ]
    }
  ],
  "totalCollections": 9
}
```

---

### Comparison

#### `POST /api/compare`
Compare multiple watches side-by-side.

**Request Body:**
```json
{
  "watchIds": [
    "speedmaster-moonwatch-1969",
    "seamaster-300-1957"
  ]
}
```

**Example Request:**
```bash
curl -X POST http://45.61.58.125:7600/api/compare \
  -H "Content-Type: application/json" \
  -d '{
    "watchIds": [
      "speedmaster-moonwatch-1969",
      "seamaster-300-1957"
    ]
  }'
```

**Example Response:**
```json
{
  "watches": [
    {
      "id": "speedmaster-moonwatch-1969",
      "model": "Speedmaster Professional Moonwatch",
      "series": "Speedmaster",
      "yearIntroduced": 1963,
      "currentPrice": 125000,
      "appreciation": 131478.95,
      "priceHistory": [...]
    },
    {
      "id": "seamaster-300-1957",
      "model": "Seamaster 300",
      "series": "Seamaster",
      "yearIntroduced": 1957,
      "currentPrice": 85000,
      "appreciation": 42400.00,
      "priceHistory": [...]
    }
  ],
  "count": 2
}
```

**Constraints:**
- Minimum 2 watches
- Maximum 10 watches per comparison

---

### Export

#### `GET /api/export/{format}`
Export complete database.

**Path Parameters:**
- `format` (required): Export format (`json` or `csv`)

**Example Request (JSON):**
```bash
curl http://45.61.58.125:7600/api/export/json -o watches.json
```

**Example Request (CSV):**
```bash
curl http://45.61.58.125:7600/api/export/csv -o watches.csv
```

**CSV Format:**
```csv
ID,Model,Series,Reference,Year Introduced,Current Price,Original Price,Appreciation %
speedmaster-moonwatch-1969,"Speedmaster Professional Moonwatch ST 105.012",Speedmaster,ST 105.012,1963,125000,95,131478.95
```

---

## SDKs & Client Libraries

### JavaScript/TypeScript SDK

#### Installation
```bash
npm install @omega-watches/api-client
```

Or copy the standalone SDK:
```bash
curl -O http://45.61.58.125:7600/sdk/omega-api-client.js
```

#### Basic Usage
```javascript
import OmegaWatchAPI from '@omega-watches/api-client';

// Initialize client
const api = new OmegaWatchAPI({
  baseURL: 'http://45.61.58.125:7600',
  timeout: 10000
});

// Get watches
const watches = await api.getWatches({
  series: 'Speedmaster',
  minYear: 1960,
  limit: 10
});

console.log(`Found ${watches.total} watches`);

// Search
const results = await api.search('moonwatch', {
  movement: 'manual',
  minPrice: 50000
});

// Get predictions
const predictions = await api.getPricePredictions('speedmaster-moonwatch-1969');
console.log(`Trend: ${predictions.trend}`);
console.log(`2026 Prediction: $${predictions.predictions[0].predictedPrice}`);

// Get statistics
const stats = await api.getStatistics();
console.log(`Average appreciation: ${stats.averageAppreciation}%`);
```

#### WebSocket Support
```javascript
// Connect to WebSocket
api.connectWebSocket({
  onUpdate: (data) => {
    console.log('Price update:', data);
  },
  onError: (error) => {
    console.error('WebSocket error:', error);
  },
  onConnect: () => {
    console.log('Connected to WebSocket');
  }
});

// Subscribe to watch updates
api.subscribeToWatch('speedmaster-moonwatch-1969');

// Disconnect
api.disconnectWebSocket();
```

#### Error Handling
```javascript
try {
  const watch = await api.getWatchById('invalid-id');
} catch (error) {
  if (error.statusCode === 404) {
    console.log('Watch not found');
  } else {
    console.error('API error:', error.message);
  }
}
```

---

### Python SDK

#### Installation
```bash
pip install omega-watch-api
```

Or copy the standalone SDK:
```bash
curl -O http://45.61.58.125:7600/sdk/omega_api_client.py
```

#### Basic Usage
```python
from omega_api_client import OmegaWatchAPI

# Initialize
api = OmegaWatchAPI(base_url='http://45.61.58.125:7600')

# Get watches
watches = api.get_watches(series='Speedmaster', min_year=1960, limit=10)
print(f"Found {watches['total']} watches")

# Search
results = api.search('moonwatch', movement='manual', min_price=50000)
for watch in results['results']:
    print(f"- {watch['model']}")

# Get predictions
predictions = api.get_price_predictions('speedmaster-moonwatch-1969')
print(f"Trend: {predictions['trend']}")
print(f"2026 Prediction: ${predictions['predictions'][0]['predictedPrice']:,}")

# Get statistics
stats = api.get_statistics()
print(f"Average appreciation: {stats['averageAppreciation']:.2f}%")

# Context manager (automatic cleanup)
with OmegaWatchAPI() as api:
    health = api.get_health()
    print(f"Status: {health['status']}")
```

#### Error Handling
```python
from omega_api_client import OmegaWatchAPI, OmegaWatchAPIError

api = OmegaWatchAPI()

try:
    watch = api.get_watch_by_id('invalid-id')
except OmegaWatchAPIError as e:
    if e.status_code == 404:
        print('Watch not found')
    else:
        print(f'API error: {e}')
```

---

## Code Examples

### Example 1: Find Best Investment Opportunities

```javascript
const api = new OmegaWatchAPI();

// Get all watches
const allWatches = await api.getWatches({ limit: 100 });

// Calculate ROI and sort
const opportunities = allWatches.watches
  .map(watch => {
    const history = watch.priceHistory;
    if (history.length < 2) return null;

    const original = history[0].price;
    const current = history[history.length - 1].price;
    const roi = ((current - original) / original) * 100;
    const years = history[history.length - 1].year - history[0].year;
    const annualizedROI = roi / years;

    return {
      model: watch.model,
      roi,
      annualizedROI,
      currentPrice: current
    };
  })
  .filter(Boolean)
  .sort((a, b) => b.annualizedROI - a.annualizedROI);

// Top 5 opportunities
console.log('Top 5 Investment Opportunities:');
opportunities.slice(0, 5).forEach((watch, i) => {
  console.log(`${i + 1}. ${watch.model}`);
  console.log(`   ROI: ${watch.roi.toFixed(2)}%`);
  console.log(`   Annualized: ${watch.annualizedROI.toFixed(2)}%/year`);
});
```

### Example 2: Price Trend Analysis

```python
import matplotlib.pyplot as plt
from omega_api_client import OmegaWatchAPI

api = OmegaWatchAPI()

# Get watch history
watch = api.get_watch_by_id('speedmaster-moonwatch-1969')
history = watch['priceHistory']

# Extract data
years = [p['year'] for p in history]
prices = [p['price'] for p in history]

# Plot
plt.figure(figsize=(12, 6))
plt.plot(years, prices, marker='o', linewidth=2, markersize=8)
plt.title(f"{watch['watch']['model']} - Price History", fontsize=16)
plt.xlabel('Year', fontsize=12)
plt.ylabel('Price (USD)', fontsize=12)
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('price_history.png')

print(f"Chart saved to price_history.png")
```

### Example 3: Collection Comparison

```javascript
const api = new OmegaWatchAPI();

// Get all collections
const { collections } = await api.getCollections();

// Compare by appreciation
const comparison = collections
  .map(coll => ({
    series: coll.series,
    count: coll.count,
    avgPrice: coll.avgPrice,
    avgAppreciation: coll.avgAppreciation
  }))
  .sort((a, b) => b.avgAppreciation - a.avgAppreciation);

console.log('Collection Performance Ranking:');
console.log('═══════════════════════════════════════════════════');

comparison.forEach((coll, i) => {
  console.log(`${i + 1}. ${coll.series}`);
  console.log(`   Watches: ${coll.count}`);
  console.log(`   Avg Price: $${coll.avgPrice.toLocaleString()}`);
  console.log(`   Avg Appreciation: ${coll.avgAppreciation.toFixed(2)}%`);
  console.log('');
});
```

### Example 4: Real-time Price Monitoring

```javascript
const api = new OmegaWatchAPI();

// Track specific watches
const watchlist = [
  'speedmaster-moonwatch-1969',
  'seamaster-300-1957',
  'constellation-1952'
];

// Connect to WebSocket
api.connectWebSocket({
  onConnect: () => {
    console.log('Connected to real-time updates');

    // Subscribe to each watch
    watchlist.forEach(watchId => {
      api.subscribeToWatch(watchId);
      console.log(`Subscribed to ${watchId}`);
    });
  },

  onUpdate: (data) => {
    console.log(`[${new Date().toISOString()}] Update for ${data.watchId}`);
    console.log(`  New price: $${data.data.price}`);
    console.log(`  Change: ${data.data.change}%`);
  },

  onError: (error) => {
    console.error('WebSocket error:', error);
  }
});

// Keep connection alive
process.on('SIGINT', () => {
  api.disconnectWebSocket();
  process.exit();
});
```

---

## WebSocket API

### Connection
```javascript
const ws = new WebSocket('ws://45.61.58.125:7600');

ws.onopen = () => {
  console.log('Connected');

  // Subscribe to watch
  ws.send(JSON.stringify({
    type: 'subscribe',
    watchId: 'speedmaster-moonwatch-1969'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);

  switch (data.type) {
    case 'subscribed':
      console.log('Subscribed to:', data.watchId);
      break;

    case 'update':
      console.log('Price update:', data.data);
      break;
  }
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('Disconnected');
};
```

### Message Types

**Subscribe to Watch:**
```json
{
  "type": "subscribe",
  "watchId": "speedmaster-moonwatch-1969"
}
```

**Subscription Confirmation:**
```json
{
  "type": "subscribed",
  "watchId": "speedmaster-moonwatch-1969"
}
```

**Price Update:**
```json
{
  "type": "update",
  "watchId": "speedmaster-moonwatch-1969",
  "data": {
    "price": 126500,
    "change": 1.2,
    "timestamp": "2025-11-17T10:30:00.000Z"
  }
}
```

---

## Error Handling

### HTTP Status Codes

| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Successful request |
| 400 | Bad Request | Invalid parameters or malformed request |
| 404 | Not Found | Resource doesn't exist |
| 500 | Internal Server Error | Server error - contact support |

### Error Response Format

All errors return a consistent JSON structure:

```json
{
  "error": "Error message",
  "details": "Additional error information"
}
```

### Common Errors

**Watch Not Found (404):**
```json
{
  "error": "Watch not found"
}
```

**Invalid Query Parameters (400):**
```json
{
  "error": "Invalid query parameters",
  "details": "limit must be between 1 and 100"
}
```

**Missing Required Fields (400):**
```json
{
  "error": "watchIds array is required"
}
```

### Retry Strategy

Implement exponential backoff for failed requests:

```javascript
async function fetchWithRetry(url, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url);
      if (response.ok) return await response.json();

      if (response.status >= 500) {
        // Server error - retry
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }

      // Client error - don't retry
      throw new Error(`HTTP ${response.status}`);

    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
```

---

## Rate Limiting & Best Practices

### Current Limits
- No rate limiting enforced
- Fair usage expected

### Best Practices

1. **Cache Responses**
   ```javascript
   const cache = new Map();

   async function getCachedWatches(series) {
     const cacheKey = `watches:${series}`;

     if (cache.has(cacheKey)) {
       const { data, timestamp } = cache.get(cacheKey);

       // Cache for 5 minutes
       if (Date.now() - timestamp < 5 * 60 * 1000) {
         return data;
       }
     }

     const data = await api.getWatches({ series });
     cache.set(cacheKey, { data, timestamp: Date.now() });
     return data;
   }
   ```

2. **Use Pagination**
   ```javascript
   // Bad: Load all at once
   const all = await api.getWatches({ limit: 1000 });

   // Good: Use pagination
   for (let page = 1; page <= totalPages; page++) {
     const watches = await api.getWatches({ page, limit: 50 });
     processWatches(watches.watches);
   }
   ```

3. **Use WebSocket for Real-time Updates**
   ```javascript
   // Bad: Poll every second
   setInterval(async () => {
     const watch = await api.getWatchById(id);
   }, 1000);

   // Good: Use WebSocket
   api.connectWebSocket({
     onUpdate: (data) => handleUpdate(data)
   });
   api.subscribeToWatch(id);
   ```

4. **Batch Requests**
   ```javascript
   // Bad: Multiple individual requests
   const watch1 = await api.getWatchById(id1);
   const watch2 = await api.getWatchById(id2);

   // Good: Use compare endpoint
   const comparison = await api.compareWatches([id1, id2]);
   ```

---

## Versioning & Migration

### Current Version: v2.0.0

### Version History

**v2.0.0 (2025-11-17)**
- Added comprehensive OpenAPI 3.0 specification
- Introduced JavaScript and Python SDKs
- Added WebSocket support for real-time updates
- Enhanced caching with stale-while-revalidate
- Added Swagger UI documentation
- Improved error messages

**v1.0.0 (Initial Release)**
- Basic REST API endpoints
- JSON/CSV export
- Price predictions
- Collection statistics

### Breaking Changes

None in v2.0.0 - Fully backward compatible with v1.0.0

### Future Roadmap

**v2.1.0 (Planned)**
- Rate limiting implementation
- Authentication for user-specific features
- Webhooks for price alerts
- GraphQL support

**v3.0.0 (Future)**
- Database migration to PostgreSQL
- Enhanced ML predictions
- Real-time market data integration

### Deprecation Policy

- 6 months notice before breaking changes
- Deprecation warnings in responses
- Migration guides provided

---

## Testing with Postman

### Import Collection

1. Download Postman collection:
   ```bash
   curl -O http://45.61.58.125:7600/postman_collection.json
   ```

2. Import into Postman:
   - Open Postman
   - Click "Import"
   - Select downloaded file

### Environment Variables

Set these variables in Postman:
- `baseUrl`: `http://45.61.58.125:7600`
- `apiKey`: (your API key for admin endpoints)

### Run Collection

Use Postman Collection Runner to test all endpoints automatically.

---

## Common Use Cases

### Use Case 1: Build a Price Tracker Dashboard

```javascript
const api = new OmegaWatchAPI();

async function buildDashboard() {
  // Get market overview
  const stats = await api.getStatistics();

  // Get trending watches
  const trending = await api.getTrending(10);

  // Get top performers
  const topPerformers = stats.topPerformers.slice(0, 5);

  // Display
  console.log('Market Overview');
  console.log('═══════════════════════════════════════');
  console.log(`Total Watches: ${stats.totalWatches}`);
  console.log(`Average Appreciation: ${stats.averageAppreciation}%`);
  console.log('');

  console.log('Top Performers:');
  topPerformers.forEach((watch, i) => {
    console.log(`${i + 1}. ${watch.model}`);
    console.log(`   Appreciation: ${watch.appreciation}%`);
  });
  console.log('');

  console.log('Trending Now:');
  trending.trending.forEach((watch, i) => {
    console.log(`${i + 1}. ${watch.model} (${watch.views} views)`);
  });
}

buildDashboard();
```

### Use Case 2: Investment Portfolio Tracker

```python
from omega_api_client import OmegaWatchAPI

api = OmegaWatchAPI()

# Your portfolio
portfolio = [
    {'watch_id': 'speedmaster-moonwatch-1969', 'quantity': 1, 'purchase_price': 80000},
    {'watch_id': 'seamaster-300-1957', 'quantity': 2, 'purchase_price': 60000}
]

# Calculate portfolio value
total_value = 0
total_cost = 0

print('Investment Portfolio')
print('═══════════════════════════════════════════════════════════')

for item in portfolio:
    watch = api.get_watch_by_id(item['watch_id'])
    current_price = watch['priceHistory'][-1]['price']

    item_value = current_price * item['quantity']
    item_cost = item['purchase_price'] * item['quantity']
    item_gain = item_value - item_cost
    item_roi = (item_gain / item_cost) * 100

    total_value += item_value
    total_cost += item_cost

    print(f"\n{watch['watch']['model']}")
    print(f"  Quantity: {item['quantity']}")
    print(f"  Purchase Price: ${item['purchase_price']:,}")
    print(f"  Current Price: ${current_price:,}")
    print(f"  Value: ${item_value:,}")
    print(f"  Gain/Loss: ${item_gain:,} ({item_roi:+.2f}%)")

total_gain = total_value - total_cost
total_roi = (total_gain / total_cost) * 100

print('\n═══════════════════════════════════════════════════════════')
print(f"Total Investment: ${total_cost:,}")
print(f"Current Value: ${total_value:,}")
print(f"Total Gain/Loss: ${total_gain:,} ({total_roi:+.2f}%)")
```

### Use Case 3: Automated Price Alerts

```javascript
const api = new OmegaWatchAPI();

// Define alert rules
const alerts = [
  {
    watchId: 'speedmaster-moonwatch-1969',
    threshold: 130000,
    direction: 'above'
  },
  {
    watchId: 'seamaster-300-1957',
    threshold: 70000,
    direction: 'below'
  }
];

// Check prices
async function checkAlerts() {
  for (const alert of alerts) {
    const watch = await api.getWatchById(alert.watchId);
    const currentPrice = watch.priceHistory[watch.priceHistory.length - 1].price;

    const triggered = alert.direction === 'above'
      ? currentPrice > alert.threshold
      : currentPrice < alert.threshold;

    if (triggered) {
      console.log(`ALERT: ${watch.watch.model}`);
      console.log(`  Current Price: $${currentPrice.toLocaleString()}`);
      console.log(`  Threshold: $${alert.threshold.toLocaleString()} (${alert.direction})`);

      // Send notification (email, SMS, etc.)
      await sendNotification(alert, currentPrice);
    }
  }
}

// Run every hour
setInterval(checkAlerts, 60 * 60 * 1000);
```

---

## Troubleshooting

### Issue: Connection Timeout

**Symptom:** Requests timeout after 10 seconds

**Solution:**
```javascript
// Increase timeout in SDK
const api = new OmegaWatchAPI({
  baseURL: 'http://45.61.58.125:7600',
  timeout: 30000 // 30 seconds
});
```

### Issue: WebSocket Disconnects

**Symptom:** WebSocket connection drops frequently

**Solution:**
```javascript
// Implement reconnection logic
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

api.connectWebSocket({
  onError: () => {
    if (reconnectAttempts < maxReconnectAttempts) {
      setTimeout(() => {
        reconnectAttempts++;
        api.connectWebSocket(config);
      }, 2000 * Math.pow(2, reconnectAttempts));
    }
  },
  onConnect: () => {
    reconnectAttempts = 0;
  }
});
```

### Issue: 404 Watch Not Found

**Symptom:** Getting 404 for valid watch IDs

**Solution:**
```bash
# Get list of valid IDs
curl http://45.61.58.125:7600/api/watches?limit=100 | jq '.watches[].id'
```

### Issue: Slow Response Times

**Symptom:** API responses take >5 seconds

**Solution:**
1. Check server health: `curl http://45.61.58.125:7600/api/health`
2. Use pagination: Reduce `limit` parameter
3. Cache responses on client side
4. Clear server cache: `POST /api/admin/clear-cache`

---

## Support & Resources

### Documentation
- **Interactive Docs**: http://45.61.58.125:7600/api/docs/swagger
- **OpenAPI Spec**: http://45.61.58.125:7600/api/docs/openapi.json
- **This Guide**: http://45.61.58.125:7600/docs/API_COMPLETE_GUIDE.md

### Health & Status
- **Health Check**: http://45.61.58.125:7600/api/health
- **System Status**: Monitor `/api/health` for uptime

### Additional Resources
- Postman Collection: http://45.61.58.125:7600/postman_collection.json
- JavaScript SDK: http://45.61.58.125:7600/sdk/omega-api-client.js
- Python SDK: http://45.61.58.125:7600/sdk/omega_api_client.py

---

## License

MIT License - See LICENSE file for details

---

**Last Updated:** 2025-11-17
**API Version:** 2.0.0