Files
2026-02-04 16:54:36 +10:00

10 KiB

Subtask: URL Creation and Management API

Parent Task: Decomp/001 Subtask ID: Decomp/001-11 Dependencies: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62), Decomp/001-03 (Short Code Generation)

Description

Implement REST API for creating, retrieving, updating, and deleting shortened URLs. This is the primary user-facing API that ties together the database, encoding, and code generation components.

Requirements

  • Create short URL from long URL
  • Support custom aliases
  • Retrieve URL details (metadata)
  • Update existing URLs
  • Delete URLs (soft delete)
  • Batch URL creation
  • Input validation and error handling
  • API authentication (optional API key)

Technical Specifications

Base URL: /api/v1/

Data models:

from datetime import datetime
from typing import Optional
from pydantic import BaseModel, HttpUrl, Field

class CreateURLRequest(BaseModel):
    """Request to create a shortened URL."""
    url: HttpUrl = Field(..., description="Original URL to shorten")
    custom_alias: Optional[str] = Field(
        None,
        min_length=3,
        max_length=20,
        pattern=r'^[a-zA-Z0-9-_]+$',
        description="Custom short code (optional)"
    )
    ttl_seconds: Optional[int] = Field(
        None,
        gt=0,
        le=31536000,  # Max 1 year
        description="Time-to-live in seconds"
    )
    expires_at: Optional[datetime] = Field(
        None,
        description="Absolute expiration timestamp"
    )
    permanent: Optional[bool] = Field(
        False,
        description="If true, URL never expires"
    )
    metadata: Optional[dict] = Field(
        None,
        description="Custom metadata for URL"
    )

class URLResponse(BaseModel):
    """Response with URL details."""
    short_code: str
    short_url: str
    original_url: str
    created_at: datetime
    expires_at: Optional[datetime]
    is_permanent: bool
    click_count: int
    custom_alias: bool
    qr_code_url: str

class UpdateURLRequest(BaseModel):
    """Request to update an existing URL."""
    url: Optional[HttpUrl] = None
    expires_at: Optional[datetime] = None
    permanent: Optional[bool] = None
    metadata: Optional[dict] = None

class BatchCreateRequest(BaseModel):
    """Request to create multiple URLs."""
    urls: list[CreateURLRequest]
    Field(..., min_length=1, max_length=100)

API endpoints:

from flask import Flask, request, jsonify
from http import HTTPStatus

app = Flask(__name__)

# POST /api/v1/shorten - Create short URL
@app.route('/api/v1/shorten', methods=['POST'])
@rate_limit('create_url')
def create_short_url():
    """
    Create a new shortened URL.

    Request:
    {
        "url": "https://example.com/very/long/path",
        "custom_alias": "mylink",  // optional
        "ttl_seconds": 86400,      // optional
        "permanent": false         // optional
    }

    Response 201:
    {
        "short_code": "abc123",
        "short_url": "https://sh.rt/abc123",
        "original_url": "https://example.com/very/long/path",
        "created_at": "2025-02-04T12:00:00Z",
        "expires_at": "2025-02-05T12:00:00Z",
        "is_permanent": false,
        "click_count": 0,
        "custom_alias": false,
        "qr_code_url": "https://sh.rt/qr/abc123"
    }

    Errors:
    - 400: Invalid input
    - 409: Custom alias already exists
    - 422: Unprocessable entity (invalid URL)
    - 429: Rate limit exceeded
    """
    try:
        data = CreateURLRequest(**request.get_json())
    except ValidationError as e:
        return jsonify({'error': 'Validation failed', 'details': e.errors()}), 400

    # Check for duplicate URL (if enabled)
    existing = find_duplicate_url(data.url)
    if existing:
        return jsonify(URLResponse.from_db_row(existing)), 200  # Already exists

    # Handle custom alias
    if data.custom_alias:
        if not is_alias_available(data.custom_alias):
            return jsonify({
                'error': 'Custom alias already taken',
                'alias': data.custom_alias
            }), 409
        short_code = data.custom_alias
    else:
        # Generate unique short code
        short_code = generate_unique_short_code()

    # Calculate expiration
    expires_at = calculate_expiration(
        ttl_seconds=data.ttl_seconds,
        expires_at=data.expires_at,
        permanent=data.permanent
    )

    # Store in database
    url_id = insert_url(
        short_code=short_code,
        original_url=str(data.url),
        expires_at=expires_at,
        is_permanent=data.permanent or expires_at is None,
        custom_alias=bool(data.custom_alias),
        metadata=data.metadata
    )

    # Build response
    response = URLResponse(
        short_code=short_code,
        short_url=f"{BASE_URL}/{short_code}",
        original_url=str(data.url),
        created_at=datetime.now(timezone.utc),
        expires_at=expires_at,
        is_permanent=data.permanent or expires_at is None,
        click_count=0,
        custom_alias=bool(data.custom_alias),
        qr_code_url=f"{BASE_URL}/qr/{short_code}"
    )

    return jsonify(response.dict()), 201


# GET /api/v1/urls/:short_code - Get URL details
@app.route('/api/v1/urls/<short_code>', methods=['GET'])
@rate_limit('analytics')
def get_url_details(short_code: str):
    """
    Retrieve details for a shortened URL.

    Response 200: URLResponse object
    Response 404: URL not found
    """
    url = get_url_by_short_code(short_code)
    if not url:
        return jsonify({'error': 'URL not found'}), 404

    return jsonify(URLResponse.from_db_row(url)), 200


# PUT /api/v1/urls/:short_code - Update URL
@app.route('/api/v1/urls/<short_code>', methods=['PUT'])
@rate_limit('create_url')  # Same limits as creation
def update_url(short_code: str):
    """
    Update an existing URL.

    Request: Partial UpdateURLRequest

    Note: Cannot change short_code once created.

    Response 200: Updated URLResponse
    Response 404: URL not found
    """
    url = get_url_by_short_code(short_code)
    if not url:
        return jsonify({'error': 'URL not found'}), 404

    data = UpdateURLRequest(**request.get_json())

    # Apply updates
    updates = {}
    if data.url:
        updates['original_url'] = str(data.url)
    if data.expires_at is not None:
        updates['expires_at'] = data.expires_at
    if data.permanent is not None:
        updates['is_permanent'] = data.permanent
    if data.metadata is not None:
        updates['metadata'] = data.metadata

    if updates:
        update_url_in_db(url['id'], updates)
        # Invalidate cache
        invalidate_cache(short_code)

    return jsonify(URLResponse.from_db_row(get_url_by_short_code(short_code))), 200


# DELETE /api/v1/urls/:short_code - Delete URL
@app.route('/api/v1/urls/<short_code>', methods=['DELETE'])
@rate_limit('create_url')
def delete_url(short_code: str):
    """
    Delete a shortened URL (soft delete).

    Response 204: No content (success)
    Response 404: URL not found
    """
    url = get_url_by_short_code(short_code)
    if not url:
        return jsonify({'error': 'URL not found'}), 404

    # Soft delete: mark as deleted
    soft_delete_url(url['id'])

    # Invalidate cache
    invalidate_cache(short_code)

    return '', 204


# POST /api/v1/shorten/batch - Batch create URLs
@app.route('/api/v1/shorten/batch', methods=['POST'])
@rate_limit('create_url')  # Higher limit for batch
def create_short_urls_batch():
    """
    Create multiple shortened URLs in one request.

    Request:
    {
        "urls": [
            {"url": "https://example1.com"},
            {"url": "https://example2.com", "custom_alias": "link2"}
        ]
    }

    Response 201:
    {
        "urls": [URLResponse, ...],
        "failed": [
            {"index": 0, "error": "reason"}
        ]
    }

    Allows partial success: some URLs may fail while others succeed.
    """
    data = BatchCreateRequest(**request.get_json())

    results = []
    failed = []

    for i, url_req in enumerate(data.urls):
        try:
            # Create URL (reuse logic from single create)
            result = create_single_url(url_req)
            results.append(result)
        except Exception as e:
            failed.append({
                'index': i,
                'url': str(url_req.url),
                'error': str(e)
            })

    return jsonify({
        'urls': results,
        'failed': failed
    }), 201 if results and not failed else 207  # 207 for multi-status

Validation helper:

def is_alias_available(alias: str) -> bool:
    """Check if custom alias is not already taken."""
    return not url_exists_by_short_code(alias)

def find_duplicate_url(url: str) -> Optional[dict]:
    """
    Find existing URL with same target (deduplication).

    Can be disabled via config if not desired.
    """
    if not ENABLE_DEDUPLICATION:
        return None
    return get_url_by_original_url(url)

Acceptance Criteria

  • Create URL returns valid short code
  • Custom alias works when available
  • Custom alias rejected when taken (409)
  • Duplicate URL detection returns existing URL
  • Update endpoint modifies only specified fields
  • Delete endpoint soft-deletes URL
  • Batch create handles partial failures
  • All endpoints return proper HTTP status codes

Notes

Trade-offs:

  • Duplicate detection: Optional, may not be desired in all cases
  • Soft delete vs hard delete: Soft preserves analytics
  • Synchronous vs async creation: Synchronous for immediate feedback

Edge cases:

  • Very long original URLs: Truncate at DB limit (2048 chars)
  • Custom alias collision: Return helpful error message
  • Concurrent creation of same alias: Second request fails

Performance:

  • Index on short_code for O(1) lookups
  • Index on original_url hash for duplicate detection
  • Cache invalidation on update/delete

Security:

  • URL validation: Prevent javascript: and data: schemes
  • Rate limiting: Applied to all write operations
  • Input sanitization: Escape HTML in metadata

Alternatives considered:

  • Hard delete: Rejected, loses analytics
  • Async creation: Rejected, adds complexity
  • No duplicate detection: Default to disabled