# Dubai Analytics Platform API Documentation

## Overview

The Dubai Analytics Platform provides a comprehensive REST API for accessing real estate market data, analytics, and insights. All API endpoints require authentication via API key.

## Base URL

```
http://localhost:8000/api/v1/
```

## Authentication

All API requests must include your API key in the request headers. You can pass the API key in two ways:

### Method 1: X-API-Key Header (Recommended)
```bash
X-API-Key: your_api_key_here
```

### Method 2: Authorization Header
```bash
Authorization: ApiKey your_api_key_here
```

## Getting Your API Key

### 1. Register a New User
```bash
curl -X POST http://localhost:8000/api/v1/auth/register/ \
  -H "Content-Type: application/json" \
  -d '{
    "username": "your_username",
    "email": "your_email@example.com",
    "password": "your_password",
    "first_name": "Your",
    "last_name": "Name",
    "company_name": "Your Company"
  }'
```

### 2. Enable API Access and Get API Key
```bash
curl -X POST http://localhost:8000/api/v1/auth/toggle-api-access/ \
  -H "Authorization: Bearer your_jwt_token" \
  -H "Content-Type: application/json"
```

### 3. Regenerate API Key (if needed)
```bash
curl -X POST http://localhost:8000/api/v1/auth/regenerate-api-key/ \
  -H "Authorization: Bearer your_jwt_token" \
  -H "Content-Type: application/json"
```

## API Endpoints

### Authentication Endpoints

#### Register User
```bash
curl -X POST http://localhost:8000/api/v1/auth/register/ \
  -H "Content-Type: application/json" \
  -d '{
    "username": "john_doe",
    "email": "john@example.com",
    "password": "secure_password123",
    "first_name": "John",
    "last_name": "Doe",
    "company_name": "Real Estate Corp"
  }'
```

#### Login
```bash
curl -X POST http://localhost:8000/api/v1/auth/login/ \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "secure_password123"
  }'
```

#### Get User Profile
```bash
curl -X GET http://localhost:8000/api/v1/auth/user/ \
  -H "Authorization: Bearer your_jwt_token"
```

### Analytics Endpoints

#### 1. Broker Statistics
Get comprehensive broker statistics including gender distribution, nationality breakdown, and license information.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/broker-stats/" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "gender_distribution": [
    {"gender": "male", "count": 1250},
    {"gender": "female", "count": 890}
  ],
  "nationality_distribution": [
    {"nationality": "UAE", "count": 800},
    {"nationality": "India", "count": 650}
  ],
  "license_status_distribution": [
    {"status": "Active", "count": 1800},
    {"status": "Inactive", "count": 340}
  ]
}
```

#### 2. Project Statistics
Get project development statistics including status distribution, completion rates, and developer information.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/project-stats/" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "status_distribution": [
    {"project_status": "ACTIVE", "count": 45},
    {"project_status": "COMPLETED", "count": 120},
    {"project_status": "PLANNED", "count": 25}
  ],
  "developer_distribution": [
    {"developer": "Emaar Properties", "count": 35},
    {"developer": "Nakheel", "count": 28}
  ]
}
```

#### 3. Land Statistics
Get land parcel statistics including type distribution, area analysis, and usage patterns.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/land-stats/" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "type_distribution": [
    {"land_type": "Residential", "count": 450},
    {"land_type": "Commercial", "count": 280},
    {"land_type": "Mixed Use", "count": 120}
  ],
  "area_distribution": [
    {"area_range": "0-1000", "count": 200},
    {"area_range": "1000-5000", "count": 350}
  ]
}
```

#### 4. Valuation Statistics
Get property valuation statistics including price trends, market analysis, and valuation methods.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/valuation-stats/" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "valuation_method_distribution": [
    {"method": "Sales Comparison", "count": 1200},
    {"method": "Income Approach", "count": 800}
  ],
  "property_type_distribution": [
    {"property_type": "Apartment", "count": 1500},
    {"property_type": "Villa", "count": 900}
  ]
}
```

#### 5. Rent Statistics
Get rental market statistics including rent trends, property types, and area analysis.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/rent-stats/" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "property_type_distribution": [
    {"property_type": "Apartment", "count": 800},
    {"property_type": "Villa", "count": 400}
  ],
  "rent_range_distribution": [
    {"range": "0-5000", "count": 200},
    {"range": "5000-10000", "count": 500}
  ]
}
```

#### 6. Time Series Data
Get time-series data for transactions, values, and market trends.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/time-series-data/?start_date=2025-01-01&end_date=2025-12-31&group_by=month" \
  -H "X-API-Key: your_api_key_here"
```

**Parameters:**
- `start_date`: Start date in YYYY-MM-DD format
- `end_date`: End date in YYYY-MM-DD format
- `group_by`: Grouping interval (day, week, month, quarter, year)

**Response:**
```json
{
  "data": [
    {
      "date": "2025-01-01",
      "transaction_count": 150,
      "total_value": 45000000,
      "average_price": 300000
    }
  ]
}
```

#### 7. Transaction Summary
Get summary statistics for transactions within a date range.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/transaction-summary/?start_date=2025-01-01&end_date=2025-12-31" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "total_transactions": 1500,
  "total_value": 450000000,
  "average_price": 300000,
  "average_price_per_sqft": 2500
}
```

#### 8. Area Statistics
Get statistics by geographic area.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/area-statistics/?start_date=2025-01-01&end_date=2025-12-31&limit=10" \
  -H "X-API-Key: your_api_key_here"
```

**Parameters:**
- `start_date`: Start date in YYYY-MM-DD format
- `end_date`: End date in YYYY-MM-DD format
- `limit`: Number of areas to return (default: 10)

**Response:**
```json
{
  "data": [
    {
      "area": "Downtown Dubai",
      "transaction_count": 150,
      "total_value": 45000000,
      "average_price": 300000,
      "average_price_per_sqft": 2500,
      "price_trend": "Rising"
    }
  ]
}
```

#### 9. Property Type Statistics
Get statistics by property type.

```bash
curl -X GET "http://localhost:8000/api/v1/analytics/property-type-statistics/?start_date=2025-01-01&end_date=2025-12-31" \
  -H "X-API-Key: your_api_key_here"
```

**Response:**
```json
{
  "data": [
    {
      "property_type": "Apartment",
      "transaction_count": 800,
      "total_value": 240000000,
      "average_price": 300000,
      "market_share": 53.3
    }
  ]
}
```

### Reports Endpoints

#### Get All Reports
```bash
curl -X GET "http://localhost:8000/api/v1/reports/" \
  -H "X-API-Key: your_api_key_here"
```

#### Generate Report
```bash
curl -X POST "http://localhost:8000/api/v1/reports/generate/" \
  -H "X-API-Key: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "report_type": "transaction_summary",
    "parameters": {
      "start_date": "2025-01-01",
      "end_date": "2025-12-31",
      "area": "Downtown Dubai"
    }
  }'
```

### Monitoring Endpoints

#### System Metrics
```bash
curl -X GET "http://localhost:8000/api/v1/monitoring/metrics/" \
  -H "X-API-Key: your_api_key_here"
```

### User Management Endpoints

#### Get User List (Admin)
```bash
curl -X GET "http://localhost:8000/api/v1/auth/list/" \
  -H "X-API-Key: your_api_key_here"
```

#### Update User Profile
```bash
curl -X PUT "http://localhost:8000/api/v1/auth/profile/" \
  -H "X-API-Key: your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "first_name": "John",
    "last_name": "Doe",
    "company_name": "Updated Company",
    "phone_number": "+971501234567"
  }'
```

## Error Handling

The API uses standard HTTP status codes:

- `200 OK`: Request successful
- `201 Created`: Resource created successfully
- `400 Bad Request`: Invalid request data
- `401 Unauthorized`: Invalid or missing API key
- `403 Forbidden`: Insufficient permissions
- `404 Not Found`: Resource not found
- `429 Too Many Requests`: Rate limit exceeded
- `500 Internal Server Error`: Server error

### Error Response Format
```json
{
  "error": "Error message",
  "details": "Detailed error information",
  "code": "ERROR_CODE"
}
```

## Rate Limiting

API requests are rate-limited based on your subscription tier:

- **Free Tier**: 100 requests/hour
- **Paid Tier**: 1,000 requests/hour
- **Premium Tier**: 10,000 requests/hour

Rate limit headers are included in responses:
- `X-RateLimit-Limit`: Requests allowed per hour
- `X-RateLimit-Remaining`: Requests remaining in current window
- `X-RateLimit-Reset`: Time when rate limit resets (Unix timestamp)

## Data Formats

### Date Format
All dates are in ISO 8601 format: `YYYY-MM-DD`

### Currency Format
All monetary values are in AED (United Arab Emirates Dirham) and returned as numbers (not formatted strings).

### Coordinates
Geographic coordinates are in decimal degrees format.

## Examples

### Complete Workflow Example

1. **Register and get API key:**
```bash
# Register user
curl -X POST http://localhost:8000/api/v1/auth/register/ \
  -H "Content-Type: application/json" \
  -d '{
    "username": "demo_user",
    "email": "demo@example.com",
    "password": "demo_password123",
    "first_name": "Demo",
    "last_name": "User",
    "company_name": "Demo Company"
  }'

# Login to get JWT token
curl -X POST http://localhost:8000/api/v1/auth/login/ \
  -H "Content-Type: application/json" \
  -d '{
    "email": "demo@example.com",
    "password": "demo_password123"
  }'

# Enable API access and get API key
curl -X POST http://localhost:8000/api/v1/auth/toggle-api-access/ \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

2. **Use API key to get data:**
```bash
# Get broker statistics
curl -X GET "http://localhost:8000/api/v1/analytics/broker-stats/" \
  -H "X-API-Key: YOUR_API_KEY"

# Get transaction summary for 2025
curl -X GET "http://localhost:8000/api/v1/analytics/transaction-summary/?start_date=2025-01-01&end_date=2025-12-31" \
  -H "X-API-Key: YOUR_API_KEY"

# Get time series data
curl -X GET "http://localhost:8000/api/v1/analytics/time-series-data/?start_date=2025-01-01&end_date=2025-12-31&group_by=month" \
  -H "X-API-Key: YOUR_API_KEY"
```

## SDKs and Libraries

### JavaScript/Node.js
```javascript
const axios = require('axios');

const api = axios.create({
  baseURL: 'http://localhost:8000/api/v1',
  headers: {
    'X-API-Key': 'your_api_key_here'
  }
});

// Get broker statistics
const brokerStats = await api.get('/analytics/broker-stats/');
console.log(brokerStats.data);
```

### Python
```python
import requests

headers = {
    'X-API-Key': 'your_api_key_here'
}

# Get broker statistics
response = requests.get('http://localhost:8000/api/v1/analytics/broker-stats/', headers=headers)
broker_stats = response.json()
print(broker_stats)
```

### PHP
```php
<?php
$api_key = 'your_api_key_here';
$headers = [
    'X-API-Key: ' . $api_key,
    'Content-Type: application/json'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:8000/api/v1/analytics/broker-stats/');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$broker_stats = json_decode($response, true);
curl_close($ch);

print_r($broker_stats);
?>
```

## Support

For API support and questions:
- Email: api-support@dubaianalytics.com
- Documentation: https://docs.dubaianalytics.com
- Status Page: https://status.dubaianalytics.com

## Changelog

### Version 1.0.0 (Current)
- Initial API release
- Authentication via API key
- All analytics endpoints
- Rate limiting by subscription tier
- Comprehensive error handling
