API Endpoints
Complete API reference with detailed endpoint documentation, request/response schemas, and usage examples.
API Endpoints
This document provides a comprehensive reference for all API endpoints in the YouTube Analyzer application, including request/response schemas, authentication requirements, and usage examples.
Base URL and Authentication
Base URL: https://vidsgenius.com/api (production) or http://localhost:3000/api (development)
Authentication: All protected endpoints require a valid session cookie. Authentication is handled via Auth.js v5 with JWT strategy.
// Authentication header format
Headers: {
'Cookie': 'authjs.session-token=...'
}Data Access Patterns
Server-side Data Access
For enhanced performance and security, certain operations bypass API routes and directly access the database from server components:
- Analysis Results: The
fetchAnalysisfunction in/app/(protected)/dashboard/results/[id]/fetchAnalysis.tsdirectly queries the database using Prisma instead of calling the/api/analysis/[id]endpoint. This avoids cross-domain cookie issues and reduces latency.
// Example of direct database access pattern
// From app/(protected)/dashboard/results/[id]/fetchAnalysis.ts
async function fetchAnalysis(id: string) {
const session = await auth();
if (!session?.user?.id) return null;
const { prisma } = await import("@/lib/db");
const analysis = await prisma.analysis.findUnique({
where: { id },
// Select fields and relations...
});
// Verify ownership and return data
if (analysis?.userId === session.user.id) {
return analysis;
}
return null;
}Important: When implementing new server components, consider direct database access for improved performance and reliability, but maintain API routes for client-side access.
Analysis Endpoints
Create Analysis
POST /api/analysis
Creates a new YouTube channel analysis.
Request Body
interface CreateAnalysisRequest {
channelUrl: string; // YouTube channel URL or @username
videoCount: number; // Number of videos to analyze (1-50)
analysisType?: string; // Optional: 'standard-summary', 'executive-summary', 'channel-deep-dive'
}Response
interface CreateAnalysisResponse {
success: boolean;
analysisId?: string;
error?: string;
}Example Usage
const response = await fetch('/api/analysis', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
channelUrl: 'https://youtube.com/@techreview',
videoCount: 10,
analysisType: 'standard-summary'
})
});
const result = await response.json();
// { success: true, analysisId: "clx..." }Status Codes
200- Analysis created successfully400- Invalid request data or insufficient credits401- Authentication required500- Internal server error
Get Analysis
GET /api/analysis/[id]
Retrieves a specific analysis with video data.
Parameters
id(string) - Analysis ID
Response
interface GetAnalysisResponse {
analysis: {
id: string;
channelUrl: string;
channel_name: string;
channel_thumbnail?: string;
videoCount: number;
htmlResult?: string;
status: 'processing' | 'completed' | 'failed';
error_message?: string;
createdAt: string;
videos: VideoData[];
};
}
interface VideoData {
id: string;
youtubeId: string;
title: string;
thumbnail?: string;
duration?: string;
viewCount?: number;
likeCount?: number;
uploadDate?: string;
channelName?: string;
}Example Usage
const response = await fetch('/api/analysis/clx123');
const { analysis } = await response.json();
console.log(analysis.status); // 'completed'
console.log(analysis.videos.length); // 10Status Codes
200- Analysis retrieved successfully401- Authentication required404- Analysis not found or access denied500- Internal server error
Auto-Analysis Endpoints
Create Auto-Analysis
POST /api/auto-analysis
Creates a new auto-analysis configuration for automated channel monitoring.
Request Body
interface CreateAutoAnalysisRequest {
channelId: string; // YouTube channel ID
channelName: string; // Display name for the channel
channelUrl: string; // YouTube channel URL
triggerType: 'per_video' | 'batch_3' | 'batch_5';
}Response
interface CreateAutoAnalysisResponse {
autoAnalysis: {
id: string;
channelId: string;
channelName: string;
channelUrl: string;
triggerType: string;
isActive: boolean;
createdAt: string;
};
}Example Usage
const response = await fetch('/api/auto-analysis', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
channelId: 'UC123456789',
channelName: 'Tech Reviews',
channelUrl: 'https://youtube.com/@techreview',
triggerType: 'batch_3'
})
});
const { autoAnalysis } = await response.json();Status Codes
201- Auto-analysis created successfully400- Invalid request data401- Authentication required403- Paid subscription required409- Auto-analysis already exists for this channel500- Internal server error
List Auto-Analyses
GET /api/auto-analysis
Retrieves all auto-analysis configurations for the authenticated user.
Response
interface ListAutoAnalysesResponse {
autoAnalyses: Array<{
id: string;
channelId: string;
channelName: string;
channelUrl: string;
triggerType: string;
isActive: boolean;
lastRunAt?: string;
totalRuns: number;
analysisCount: number;
createdAt: string;
}>;
}Example Usage
const response = await fetch('/api/auto-analysis');
const { autoAnalyses } = await response.json();
autoAnalyses.forEach(config => {
console.log(`${config.channelName}: ${config.analysisCount} analyses`);
});Update Auto-Analysis
PATCH /api/auto-analysis/[id]
Updates an existing auto-analysis configuration.
Parameters
id(string) - Auto-analysis ID
Request Body
interface UpdateAutoAnalysisRequest {
isActive?: boolean;
triggerType?: 'per_video' | 'batch_3' | 'batch_5';
}Example Usage
// Pause auto-analysis
await fetch('/api/auto-analysis/clx123', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
isActive: false
})
});Delete Auto-Analysis
DELETE /api/auto-analysis/[id]
Deletes an auto-analysis configuration.
Parameters
id(string) - Auto-analysis ID
Example Usage
await fetch('/api/auto-analysis/clx123', {
method: 'DELETE'
});Dashboard Endpoints
Recent Analyses
GET /api/dashboard/recent
Retrieves the 5 most recent analyses for the authenticated user.
Response
interface RecentAnalysesResponse {
recentAnalyses: Array<{
id: string;
channel_name?: string;
channelUrl: string;
channel_thumbnail?: string;
videoCount: number;
createdAt: string;
status: string;
summary_preview?: string;
error_message?: string;
video_thumbnail?: string;
channelName?: string;
}>;
}Example Usage
const response = await fetch('/api/dashboard/recent');
const { recentAnalyses } = await response.json();
// Display recent activity
recentAnalyses.forEach(analysis => {
console.log(`${analysis.channel_name}: ${analysis.status}`);
});Dashboard Statistics
GET /api/dashboard/stats
Retrieves dashboard statistics and metrics.
Response
interface DashboardStatsResponse {
monthlyAnalyses: number; // Analyses this month
processingCount: number; // Currently processing
apiCreditsRemaining: number; // Available credits
hasActiveSubscription: boolean; // Subscription status
}Example Usage
const response = await fetch('/api/dashboard/stats');
const stats = await response.json();
console.log(`Credits remaining: ${stats.apiCreditsRemaining}`);
console.log(`This month: ${stats.monthlyAnalyses} analyses`);YouTube Processing Endpoint
Process YouTube Analysis
POST /api/youtube/process
Core endpoint that handles the complete analysis workflow including data collection, AI processing, and result storage.
Request Body
interface YouTubeProcessRequest {
channel: string; // Channel URL or ID
count: number; // Number of videos to analyze
analysisType?: string; // Analysis type (optional)
userId?: string; // User ID (for internal use)
}Response
interface YouTubeProcessResponse {
success: boolean;
analysisId: string;
status: 'processing' | 'completed';
htmlResult?: string; // Included if completed immediately
}Process Flow
- Credit Validation - Checks and reserves user credits
- Channel Resolution - Parses channel URL and validates
- Data Collection - Fetches videos, transcripts, metadata
- AI Analysis - Processes content with OpenAI
- Result Storage - Saves analysis and video data
- Credit Deduction - Deducts credits only after success
Example Usage
const response = await fetch('/api/youtube/process', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
channel: 'https://youtube.com/@techreview',
count: 10,
analysisType: 'executive-summary'
})
});
const result = await response.json();Sharing and Communication
Share Analysis
POST /api/share-analysis
Sends an analysis result via email to a specified recipient.
Request Body
interface ShareAnalysisRequest {
email: string; // Recipient email address
analysisId: string; // Analysis to share
}Response
interface ShareAnalysisResponse {
ok: boolean;
error?: string;
}Example Usage
await fetch('/api/share-analysis', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'colleague@company.com',
analysisId: 'clx123'
})
});User Management
Delete User Account
DELETE /api/user
Permanently deletes the authenticated user's account and all associated data.
Response
interface DeleteUserResponse {
message: string;
}Example Usage
await fetch('/api/user', {
method: 'DELETE'
});⚠️ Warning: This action is irreversible and will delete all user data, analyses, and configurations.
Get User Subscription Status
GET /api/user/subscription
Retrieves the authenticated user's subscription plan information and payment status.
Response
interface UserSubscriptionResponse {
isPaid: boolean;
plan: {
title: string;
isPaid: boolean;
isCanceled: boolean;
stripeCurrentPeriodEnd?: Date;
} | null;
}Example Usage
const response = await fetch('/api/user/subscription');
const { isPaid, plan } = await response.json();
// Use for conditional features
if (isPaid) {
// Show premium features
}Status Codes
200- Subscription status retrieved successfully401- Authentication required500- Internal server error
This endpoint is used by the AnalysisActionMenu component to validate whether users can create auto-analysis subscriptions.
Webhook Endpoints
Stripe Webhooks
POST /api/webhooks/stripe
Handles Stripe webhook events for payment processing and subscription management.
Supported Events
checkout.session.completed- New subscription createdinvoice.payment_succeeded- Subscription renewedcustomer.subscription.updated- Subscription modifiedcustomer.subscription.deleted- Subscription cancelled
Webhook Security
// Webhook signature verification
const signature = req.headers['stripe-signature'];
const event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);Cron Job Endpoints
Auto-Analysis Cron
GET /api/cron/auto-analysis
Scheduled endpoint that runs auto-analysis checks for all active configurations.
Response
interface CronResponse {
results: Array<{
id: string;
status: 'triggered' | 'waiting_for_batch' | 'no_new_videos' | 'insufficient_credits';
newVideos?: number;
error?: string;
}>;
}Cron Schedule
- Frequency: Every 30 minutes
- Platform: Vercel Cron Jobs
- Configuration:
vercel.json
{
"crons": [{
"path": "/api/cron/auto-analysis",
"schedule": "*/30 * * * *"
}]
}Error Handling
Standard Error Response Format
All API endpoints follow a consistent error response format:
interface ErrorResponse {
error: string; // Human-readable error message
code?: string; // Error code for programmatic handling
details?: any; // Additional error details
}Common Error Codes
| Code | Description | HTTP Status |
|---|---|---|
UNAUTHORIZED | Authentication required | 401 |
FORBIDDEN | Insufficient permissions | 403 |
INSUFFICIENT_CREDITS | Not enough credits | 402 |
INVALID_INPUT | Request validation failed | 400 |
NOT_FOUND | Resource not found | 404 |
RATE_LIMITED | Too many requests | 429 |
EXTERNAL_API_ERROR | YouTube/OpenAI API error | 502 |
INTERNAL_ERROR | Server error | 500 |
Error Handling Example
try {
const response = await fetch('/api/analysis', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData)
});
if (!response.ok) {
const error = await response.json();
switch (error.code) {
case 'INSUFFICIENT_CREDITS':
// Redirect to billing page
window.location.href = '/dashboard/billing';
break;
case 'UNAUTHORIZED':
// Redirect to login
window.location.href = '/login';
break;
default:
// Show generic error message
alert(error.error);
}
return;
}
const result = await response.json();
// Handle success
} catch (err) {
console.error('Network error:', err);
}Rate Limiting
Rate Limit Headers
API responses include rate limit information in headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1640995200
Rate Limits by Endpoint
| Endpoint Group | Limit | Window |
|---|---|---|
| Analysis Creation | 10 requests | 1 hour |
| Dashboard Data | 100 requests | 1 hour |
| Auto-Analysis Management | 50 requests | 1 hour |
| General API | 1000 requests | 1 hour |
Pagination
For endpoints that return large datasets, pagination follows this pattern:
Request Parameters
interface PaginationParams {
page?: number; // Page number (1-based)
limit?: number; // Items per page (max 100)
sort?: string; // Sort field
order?: 'asc' | 'desc';
}Response Format
interface PaginatedResponse<T> {
data: T[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
hasNext: boolean;
hasPrev: boolean;
};
}Example Usage
const response = await fetch('/api/analysis/history?page=2&limit=20&sort=createdAt&order=desc');
const { data, pagination } = await response.json();
console.log(`Page ${pagination.page} of ${pagination.totalPages}`);
console.log(`Showing ${data.length} of ${pagination.total} analyses`);API Versioning
The API uses URL-based versioning for major changes:
- Current Version: v1 (implicit, no version prefix)
- Future Versions:
/api/v2/endpoint
Backward Compatibility
- Minor changes maintain backward compatibility
- Deprecated fields are marked but continue to work
- Breaking changes require a new version
Version Migration
// Current (v1)
const response = await fetch('/api/analysis');
// Future (v2)
const response = await fetch('/api/v2/analysis');SDK and Client Libraries
JavaScript/TypeScript SDK
import { YouTubeAnalyzerAPI } from '@vidsgenius/sdk';
const api = new YouTubeAnalyzerAPI({
baseURL: 'https://vidsgenius.com/api',
sessionToken: 'your-session-token'
});
// Create analysis
const analysis = await api.analysis.create({
channelUrl: 'https://youtube.com/@techreview',
videoCount: 10
});
// Get results
const result = await api.analysis.get(analysis.id);Python SDK
from vidsgenius import YouTubeAnalyzerAPI
api = YouTubeAnalyzerAPI(
base_url='https://vidsgenius.com/api',
session_token='your-session-token'
)
# Create analysis
analysis = api.analysis.create(
channel_url='https://youtube.com/@techreview',
video_count=10
)
# Get results
result = api.analysis.get(analysis['id'])This API reference provides comprehensive documentation for integrating with the YouTube Analyzer platform. For additional examples, testing utilities, and SDKs, refer to the developer resources section.
Prompt Management API Endpoints (2025-06-22)
The following endpoints are used for admin prompt management (all require ADMIN role):
List All Prompts
GET /api/prompts
- Returns: Array of prompt templates (id, analysisTypeKey, label, etc.)
Get Prompt with Versions
GET /api/prompts/:id
- Returns: Prompt template with all versions, metadata, and current content
Create New Prompt
POST /api/prompts
- Body:
{ analysisTypeKey, label, content } - Returns: Created prompt template
Edit/Add New Version
PATCH /api/prompts/:id
- Body:
{ newVersion: { content } } - Returns: Updated prompt with new version
Test Render Prompt
POST /api/prompts/:id/test
- Body:
{ variables, transcript } - Returns: Rendered prompt output (HTML/text)
Security
- All endpoints require authentication and ADMIN role
- All changes are versioned and auditable
Admin Tools & Prompt Management Endpoints
The API includes a set of admin-only endpoints for managing prompt templates and other administrative features:
Prompt Management Endpoints
GET /api/prompts/— List all prompt types and latest versions (admin only)GET /api/prompts/[key]— List all versions for a prompt typePOST /api/prompts/— Create a new prompt versionPATCH /api/prompts/[id]— Update a specific prompt versionDELETE /api/prompts/[id]— Delete a prompt version (soft delete)
All endpoints require admin authentication and are used by the admin UI for prompt management.
See the Admin Tools documentation for a full technical breakdown of these endpoints and their usage in the system.