# Subtask: Analytics Query API **Parent Task**: Decomp/001 **Subtask ID**: Decomp/001-08 **Dependencies**: Decomp/001-01 (Database), Decomp/001-06 (Analytics Recording) ## Description Implement API endpoints for querying URL analytics. Provide statistics, click history, and aggregated data. ## Requirements - Get click count for a short URL - Get click history with pagination - Aggregate analytics by day/country/device - Support date range filtering - <500ms response time p95 ## Technical Specifications ### API Endpoints ```http # Get URL statistics GET /api/v1/stats/{short_code} Response 200 OK: { "short_code": "abc123", "original_url": "https://example.com", "created_at": "2025-02-01T10:00:00Z", "total_clicks": 1234, "last_clicked": "2025-02-04T15:30:00Z", "expires_at": null } # Get click history with pagination GET /api/v1/analytics/{short_code}?page=1&limit=50&start_date=2025-02-01&end_date=2025-02-04 Response 200 OK: { "short_code": "abc123", "total_clicks": 1234, "page": 1, "limit": 50, "total_pages": 25, "clicks": [ { "clicked_at": "2025-02-04T15:30:00Z", "user_agent": "Mozilla/5.0...", "country_code": "US", "city": "San Francisco", "referrer": "https://google.com" } ] } # Get aggregated statistics GET /api/v1/analytics/{short_code}/aggregate?group_by=day&start_date=2025-02-01 Response 200 OK: { "short_code": "abc123", "aggregation": "day", "data": [ {"date": "2025-02-01", "clicks": 150}, {"date": "2025-02-02", "clicks": 230}, {"date": "2025-02-03", "clicks": 456}, {"date": "2025-02-04", "clicks": 398} ] } ``` ### Query Implementation ```python async def get_url_stats(short_code: str) -> dict: """Get basic statistics for a short URL.""" url_data = await db.fetch_one( """SELECT short_code, original_url, created_at, expires_at, access_count FROM urls WHERE short_code = $1""", short_code ) if not url_data: raise HTTPException(404, "Short URL not found") last_click = await db.fetch_one( """SELECT clicked_at FROM url_analytics WHERE url_id = $1 ORDER BY clicked_at DESC LIMIT 1""", url_data['id'] ) return { "short_code": url_data['short_code'], "original_url": url_data['original_url'], "created_at": url_data['created_at'].isoformat(), "total_clicks": url_data['access_count'], "last_clicked": last_click['clicked_at'].isoformat() if last_click else None, "expires_at": url_data['expires_at'].isoformat() if url_data['expires_at'] else None } async def get_click_history(short_code: str, page: int = 1, limit: int = 50, start_date: str = None, end_date: str = None) -> dict: """Get paginated click history.""" # Build query with filters conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"] params = [short_code] param_count = 1 if start_date: param_count += 1 conditions.append(f"clicked_at >= ${param_count}") params.append(start_date) if end_date: param_count += 1 conditions.append(f"clicked_at <= ${param_count}") params.append(end_date) where_clause = " AND ".join(conditions) # Get total count total = await db.fetch_one( f"SELECT COUNT(*) as count FROM url_analytics WHERE {where_clause}", *params ) total_clicks = total['count'] total_pages = (total_clicks + limit - 1) // limit # Get paginated results offset = (page - 1) * limit clicks = await db.fetch_all( f"""SELECT clicked_at, user_agent, country_code, city, referrer FROM url_analytics WHERE {where_clause} ORDER BY clicked_at DESC LIMIT ${param_count + 1} OFFSET ${param_count + 2}""", *params, limit, offset ) return { "short_code": short_code, "total_clicks": total_clicks, "page": page, "limit": limit, "total_pages": total_pages, "clicks": [dict(click) for click in clicks] } async def get_aggregated_clicks(short_code: str, group_by: str = 'day', start_date: str = None, end_date: str = None) -> dict: """Get aggregated click statistics.""" # Map group_by to SQL date truncation trunc_map = { 'day': "DATE_TRUNC('day', clicked_at)", 'hour': "DATE_TRUNC('hour', clicked_at)", 'month': "DATE_TRUNC('month', clicked_at)" } if group_by not in trunc_map: raise HTTPException(400, f"Invalid group_by: {group_by}") date_trunc = trunc_map[group_by] # Build query conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"] params = [short_code] param_count = 1 if start_date: param_count += 1 conditions.append(f"clicked_at >= ${param_count}") params.append(start_date) if end_date: param_count += 1 conditions.append(f"clicked_at <= ${param_count}") params.append(end_date) where_clause = " AND ".join(conditions) query = f""" SELECT {date_trunc} as period, COUNT(*) as clicks FROM url_analytics WHERE {where_clause} GROUP BY period ORDER BY period ASC """ results = await db.fetch_all(query, *params) return { "short_code": short_code, "aggregation": group_by, "data": [{"date": r['period'].isoformat(), "clicks": r['clicks']} for r in results] } ``` ## Acceptance Criteria - [ ] GET /api/v1/stats/{short_code} returns URL statistics - [ ] GET /api/v1/analytics/{short_code} returns paginated click history - [ ] GET /api/v1/analytics/{short_code}/aggregate returns aggregated data - [ ] Date range filtering works correctly - [ ] Pagination works correctly (page, limit, total_pages) - [ ] Group by day/hour/month supported - [ ] <500ms p95 response time - [ ] Unit tests for all endpoints ## Notes - **Database indexes**: Composite index on (url_id, clicked_at) critical for performance - **Pagination**: Cursor-based pagination better for large datasets (future enhancement) - **Caching**: Cache stats endpoint (5 minute TTL) ## Edge Cases - URL with no clicks → return 0 total_clicks - Page beyond total_pages → return empty array - Invalid date format → 400 error - Group by not supported → 400 error ## Performance Optimization - Materialized view for aggregated stats (if query is slow) - Query timeout: 5 seconds - Limit max results: 10,000 per query