> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/darkzOGx/youtube-automation-agent/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Analytics

> Retrieve recent YouTube analytics and performance data

## Endpoint

```
GET /analytics
```

## Description

Retrieves recent analytics data from YouTube, including views, engagement metrics, audience insights, and performance trends. This data is collected and analyzed by the Analytics & Optimization Agent.

## Request

No parameters required.

### Headers

No special headers required.

## Response

The response structure is determined by the Analytics & Optimization Agent's `getRecentAnalytics()` method. Typical fields include:

<ResponseField name="period" type="object">
  Time period for the analytics data.

  <ResponseField name="period.start" type="string">
    ISO 8601 start date.
  </ResponseField>

  <ResponseField name="period.end" type="string">
    ISO 8601 end date.
  </ResponseField>
</ResponseField>

<ResponseField name="overview" type="object">
  High-level performance metrics.

  <ResponseField name="overview.totalViews" type="number">
    Total video views in the period.
  </ResponseField>

  <ResponseField name="overview.totalWatchTime" type="number">
    Total watch time in minutes.
  </ResponseField>

  <ResponseField name="overview.subscribersGained" type="number">
    New subscribers in the period.
  </ResponseField>

  <ResponseField name="overview.averageViewDuration" type="number">
    Average view duration in seconds.
  </ResponseField>
</ResponseField>

<ResponseField name="topVideos" type="array">
  Best performing videos in the period.

  <ResponseField name="topVideos[].videoId" type="string">
    YouTube video ID.
  </ResponseField>

  <ResponseField name="topVideos[].title" type="string">
    Video title.
  </ResponseField>

  <ResponseField name="topVideos[].views" type="number">
    View count.
  </ResponseField>

  <ResponseField name="topVideos[].engagement" type="number">
    Engagement rate (likes, comments, shares).
  </ResponseField>
</ResponseField>

<ResponseField name="demographics" type="object">
  Audience demographic information.

  <ResponseField name="demographics.topCountries" type="array">
    Top viewer countries.
  </ResponseField>

  <ResponseField name="demographics.ageGroups" type="object">
    Age distribution of viewers.
  </ResponseField>

  <ResponseField name="demographics.gender" type="object">
    Gender distribution.
  </ResponseField>
</ResponseField>

<ResponseField name="insights" type="array">
  AI-generated insights and recommendations from the Analytics Agent.

  <ResponseField name="insights[].type" type="string">
    Insight type: `"trend"`, `"recommendation"`, `"alert"`, etc.
  </ResponseField>

  <ResponseField name="insights[].message" type="string">
    Human-readable insight description.
  </ResponseField>

  <ResponseField name="insights[].priority" type="string">
    Priority level: `"high"`, `"medium"`, `"low"`.
  </ResponseField>
</ResponseField>

<ResponseField name="error" type="string">
  Error message if the request fails.
</ResponseField>

## Example Request

<CodeGroup>
  ```bash cURL theme={null}
  curl http://localhost:3456/analytics
  ```

  ```javascript JavaScript (Fetch) theme={null}
  fetch('http://localhost:3456/analytics')
    .then(response => response.json())
    .then(data => {
      console.log('Total Views:', data.overview.totalViews);
      console.log('Top Video:', data.topVideos[0].title);
    });
  ```

  ```python Python theme={null}
  import requests

  response = requests.get('http://localhost:3456/analytics')
  analytics = response.json()

  print(f"Total Views: {analytics['overview']['totalViews']}")
  print(f"Subscribers Gained: {analytics['overview']['subscribersGained']}")

  for insight in analytics['insights']:
      print(f"💡 {insight['message']}")
  ```
</CodeGroup>

## Example Response

### Success

```json theme={null}
{
  "period": {
    "start": "2026-02-05T00:00:00.000Z",
    "end": "2026-03-05T00:00:00.000Z"
  },
  "overview": {
    "totalViews": 125430,
    "totalWatchTime": 892340,
    "subscribersGained": 1245,
    "averageViewDuration": 425,
    "engagementRate": 8.3
  },
  "topVideos": [
    {
      "videoId": "dQw4w9WgXcQ",
      "title": "Master React Hooks in 10 Minutes",
      "views": 45230,
      "engagement": 12.5,
      "publishedAt": "2026-02-20T14:00:00.000Z"
    },
    {
      "videoId": "jNQXAC9IVRw",
      "title": "10 Python Tips Every Developer Should Know",
      "views": 38920,
      "engagement": 10.8,
      "publishedAt": "2026-02-27T14:00:00.000Z"
    }
  ],
  "demographics": {
    "topCountries": [
      { "country": "US", "percentage": 42.3 },
      { "country": "IN", "percentage": 18.7 },
      { "country": "GB", "percentage": 9.2 }
    ],
    "ageGroups": {
      "18-24": 28.5,
      "25-34": 45.2,
      "35-44": 18.3,
      "45+": 8.0
    },
    "gender": {
      "male": 68.5,
      "female": 31.5
    }
  },
  "insights": [
    {
      "type": "trend",
      "message": "Tutorial content is performing 45% better than average",
      "priority": "high",
      "data": { "performanceIncrease": 45 }
    },
    {
      "type": "recommendation",
      "message": "Optimal posting time is 2 PM UTC based on audience activity",
      "priority": "medium",
      "data": { "recommendedTime": "14:00 UTC" }
    },
    {
      "type": "alert",
      "message": "Average view duration decreased by 8% - consider shorter intros",
      "priority": "high",
      "data": { "change": -8 }
    }
  ],
  "timestamp": "2026-03-05T10:30:45.123Z"
}
```

### Error

```json theme={null}
{
  "error": "Failed to fetch YouTube Analytics API data: Invalid credentials"
}
```

## Response Codes

| Status Code | Description                       |
| ----------- | --------------------------------- |
| 200         | Analytics retrieved successfully  |
| 500         | Server error retrieving analytics |

## Use Cases

### Performance Dashboard

Build a real-time analytics dashboard:

```javascript theme={null}
async function updateDashboard() {
  const response = await fetch('http://localhost:3456/analytics');
  const analytics = await response.json();
  
  document.getElementById('total-views').textContent = 
    analytics.overview.totalViews.toLocaleString();
  
  document.getElementById('subscribers').textContent = 
    '+' + analytics.overview.subscribersGained;
  
  // Display insights
  const insightsList = document.getElementById('insights');
  analytics.insights.forEach(insight => {
    const li = document.createElement('li');
    li.textContent = insight.message;
    li.className = insight.priority;
    insightsList.appendChild(li);
  });
}

// Update every 5 minutes
setInterval(updateDashboard, 5 * 60 * 1000);
```

### Automated Reporting

Generate weekly performance reports:

```python theme={null}
import requests
from datetime import datetime

def generate_weekly_report():
    response = requests.get('http://localhost:3456/analytics')
    analytics = response.json()
    
    report = f"""
    Weekly Performance Report
    Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}
    
    Overview:
    - Total Views: {analytics['overview']['totalViews']:,}
    - Subscribers Gained: {analytics['overview']['subscribersGained']:,}
    - Engagement Rate: {analytics['overview']['engagementRate']}%
    
    Top Performing Video:
    {analytics['topVideos'][0]['title']}
    ({analytics['topVideos'][0]['views']:,} views)
    
    Key Insights:
    """
    
    for insight in analytics['insights']:
        if insight['priority'] == 'high':
            report += f"\n⚠️  {insight['message']}"
    
    return report

print(generate_weekly_report())
```

### Content Strategy Optimization

Use analytics to inform content decisions:

```javascript theme={null}
async function analyzeContentStrategy() {
  const response = await fetch('http://localhost:3456/analytics');
  const analytics = await response.json();
  
  // Find best performing content types
  const topVideos = analytics.topVideos;
  const avgEngagement = topVideos.reduce((sum, v) => sum + v.engagement, 0) / topVideos.length;
  
  console.log('High-performing videos:');
  topVideos
    .filter(v => v.engagement > avgEngagement)
    .forEach(v => console.log(`- ${v.title} (${v.engagement}% engagement)`));
  
  // Check insights for recommendations
  const recommendations = analytics.insights
    .filter(i => i.type === 'recommendation');
  
  console.log('\nRecommendations:');
  recommendations.forEach(r => console.log(`- ${r.message}`));
}
```

<Note>
  Analytics data is fetched from the YouTube Analytics API. The agent caches data to avoid hitting API rate limits. Data may be up to 15 minutes old.
</Note>

## Data Freshness

The Analytics & Optimization Agent updates data on the following schedule:

* **Real-time metrics**: Updated every 15 minutes
* **Detailed analytics**: Updated every 6 hours
* **Demographic data**: Updated daily
* **AI insights**: Regenerated every 12 hours

## Privacy and Compliance

All analytics data is:

* Aggregated and anonymized per YouTube's terms
* Stored securely in the local database
* Never shared with third parties
* Compliant with YouTube's API Terms of Service
