# Subtask: URL Shortening API (Create Endpoint) **Parent Task**: Decomp/001 **Subtask ID**: Decomp/001-04 **Dependencies**: Decomp/001-01 (Database), Decomp/001-03 (Code Generation) ## Description Implement HTTP API for creating short URLs. This is the main entry point for users to shorten URLs. ## Requirements - RESTful POST endpoint for creating short URLs - Support custom alias parameter - Return short URL and metadata - Rate limiting for abuse prevention - Input validation and error handling - <200ms response time p95 ## Technical Specifications ### API Endpoint ```http POST /api/v1/shorten Content-Type: application/json { "url": "https://example.com/very/long/url", "custom_alias": "mylink" // optional } Response 201 Created: { "short_code": "abc123", "short_url": "https://short.est/abc123", "original_url": "https://example.com/very/long/url", "created_at": "2025-02-04T10:30:00Z", "expires_at": null // or ISO timestamp if set } Errors: 400 Bad Request - Invalid URL or alias 409 Conflict - Custom alias already taken 422 Unprocessable Entity - URL validation failed 429 Too Many Requests - Rate limit exceeded ``` ### Request Validation ```python def validate_shorten_request(data: dict) -> tuple[bool, str | None]: """Validate request payload.""" url = data.get('url') if not url: return False, "URL is required" # URL format validation try: result = urlparse(url) if not all([result.scheme, result.netloc]): return False, "Invalid URL format" if result.scheme not in ['http', 'https']: return False, "Only HTTP/HTTPS URLs allowed" except Exception: return False, "Invalid URL format" # Custom alias validation custom_alias = data.get('custom_alias') if custom_alias and not is_valid_alias(custom_alias): return False, "Invalid custom alias format" return True, None ``` ### Rate Limiting ```python # Redis-based rate limiting RATE_LIMIT = 10 requests per minute per IP def check_rate_limit(identifier: str) -> bool: """Check if identifier exceeded rate limit.""" key = f"ratelimit:{identifier}:{datetime.utcnow().strftime('%Y%m%d%H%M')}" count = redis.incr(key) redis.expire(key, 60) # 1 minute window return count <= RATE_LIMIT ``` ## Acceptance Criteria - [ ] POST /api/v1/shorten endpoint functional - [ ] Returns 201 with valid response body - [ ] Validates URL format (scheme, structure) - [ ] Validates custom alias format - [ ] Rate limiting enforced (10 req/min per IP) - [ ] Error responses with proper status codes - [ ] <200ms p95 latency (excluding rate limit checks) - [ ] Unit tests + integration tests ## Notes - **Framework**: Use FastAPI or Flask (async preferred) - **Rate limiting**: Redis for distributed scenarios - **Logging**: Log all URL creations for analytics - **Monitoring**: Track response times, error rates ## Edge Cases - URL with Unicode characters → punycode encoding - URL with fragments/hash → preserve in original_url - Empty request body → 400 error - Malformed JSON → 400 error - Database timeout → 503 error ## Performance Optimization - Connection pooling for database - Async I/O for database queries - Cache frequent URLs in Redis (optional optimization)