Skip to main content
GET
/
analytics
Get Analytics
curl --request GET \
  --url https://api.example.com/analytics
{
  "period": {
    "period.start": "<string>",
    "period.end": "<string>"
  },
  "overview": {
    "overview.totalViews": 123,
    "overview.totalWatchTime": 123,
    "overview.subscribersGained": 123,
    "overview.averageViewDuration": 123
  },
  "topVideos": [
    {
      "topVideos[].videoId": "<string>",
      "topVideos[].title": "<string>",
      "topVideos[].views": 123,
      "topVideos[].engagement": 123
    }
  ],
  "demographics": {
    "demographics.topCountries": [
      {}
    ],
    "demographics.ageGroups": {},
    "demographics.gender": {}
  },
  "insights": [
    {
      "insights[].type": "<string>",
      "insights[].message": "<string>",
      "insights[].priority": "<string>"
    }
  ],
  "error": "<string>"
}

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:
period
object
Time period for the analytics data.
period.start
string
ISO 8601 start date.
period.end
string
ISO 8601 end date.
overview
object
High-level performance metrics.
overview.totalViews
number
Total video views in the period.
overview.totalWatchTime
number
Total watch time in minutes.
overview.subscribersGained
number
New subscribers in the period.
overview.averageViewDuration
number
Average view duration in seconds.
topVideos
array
Best performing videos in the period.
topVideos[].videoId
string
YouTube video ID.
topVideos[].title
string
Video title.
topVideos[].views
number
View count.
topVideos[].engagement
number
Engagement rate (likes, comments, shares).
demographics
object
Audience demographic information.
demographics.topCountries
array
Top viewer countries.
demographics.ageGroups
object
Age distribution of viewers.
demographics.gender
object
Gender distribution.
insights
array
AI-generated insights and recommendations from the Analytics Agent.
insights[].type
string
Insight type: "trend", "recommendation", "alert", etc.
insights[].message
string
Human-readable insight description.
insights[].priority
string
Priority level: "high", "medium", "low".
error
string
Error message if the request fails.

Example Request

curl http://localhost:3456/analytics

Example Response

Success

{
  "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

{
  "error": "Failed to fetch YouTube Analytics API data: Invalid credentials"
}

Response Codes

Status CodeDescription
200Analytics retrieved successfully
500Server error retrieving analytics

Use Cases

Performance Dashboard

Build a real-time analytics dashboard:
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:
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:
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}`));
}
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.

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