[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73NQ7C1TGN47D80MBWJ4HH2":3,"skill-same:01M73NQ7C1TGN47D80MBWJ4HH2":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73NQ7C1TGN47D80MBWJ4HH2","api-dev",null,"Modern API development patterns for building high-performance, scalable web services. Expert in async\u002Fawait patterns, REST\u002FGraphQL APIs, middleware, error handling, rate limiting, OpenAPI documentation, testing, and production optimizations. Framework-agnostic patterns that work with Python, Node.js, Go, and other languages.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fapi-dev\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: api-dev\ndescription: Modern API development patterns for building high-performance, scalable web services. Expert in async\u002Fawait patterns, REST\u002FGraphQL APIs, middleware, error handling, rate limiting, OpenAPI documentation, testing, and production optimizations. Framework-agnostic patterns that work with Python, Node.js, Go, and other languages.\nlicense: MIT\n---\n\n# API Development Patterns & Best Practices\n\nThis skill provides comprehensive patterns for building modern APIs in 2025, focusing on async\u002Fawait patterns, performance optimization, security, testing, and production-ready configurations that work across different frameworks and languages.\n\n## When to Use This Skill\n\nUse this skill when you need to:\n- Design RESTful or GraphQL APIs\n- Implement async\u002Fawait patterns for high performance\n- Add middleware for authentication, logging, and validation\n- Handle errors gracefully with proper HTTP status codes\n- Implement rate limiting and throttling\n- Generate OpenAPI\u002FSwagger documentation\n- Set up comprehensive testing strategies\n- Optimize API performance with caching and connection pooling\n- Implement API versioning and backward compatibility\n- Set up monitoring and observability\n\n## Core API Design Principles\n\n### 1. Async\u002FAwait Patterns for Performance\n\n```python\n# patterns\u002Fasync_patterns.py\nimport asyncio\nimport aiohttp\nimport aioredis\nfrom typing import AsyncGenerator, Optional, List, Dict, Any\nfrom contextlib import asynccontextmanager\nfrom dataclasses import dataclass\nfrom functools import wraps\nimport time\n\n@dataclass\nclass RequestMetrics:\n    \"\"\"Request metrics for monitoring\"\"\"\n    duration: float\n    status_code: int\n    endpoint: str\n    method: str\n    user_id: Optional[str] = None\n\ndef with_metrics(func):\n    \"\"\"Decorator to add request metrics\"\"\"\n    @wraps(func)\n    async def wrapper(*args, **kwargs):\n        start_time = time.time()\n        status_code = 200\n        endpoint = func.__name__\n        method = kwargs.get('method', 'GET')\n\n        try:\n            result = await func(*args, **kwargs)\n            if hasattr(result, 'status_code'):\n                status_code = result.status_code\n            return result\n        except Exception as e:\n            status_code = getattr(e, 'status_code', 500)\n            raise\n        finally:\n            duration = time.time() - start_time\n            metrics = RequestMetrics(\n                duration=duration,\n                status_code=status_code,\n                endpoint=endpoint,\n                method=method\n            )\n            # Send metrics to monitoring system\n            await send_metrics(metrics)\n\n    return wrapper\n\nasync def send_metrics(metrics: RequestMetrics):\n    \"\"\"Send metrics to monitoring system\"\"\"\n    # Implementation depends on your monitoring system\n    # Example: Prometheus, Datadog, or custom analytics\n    pass\n\nclass AsyncAPIClient:\n    \"\"\"Generic async API client with connection pooling\"\"\"\n\n    def __init__(self, base_url: str, timeout: int = 30):\n        self.base_url = base_url\n        self.timeout = aiohttp.ClientTimeout(total=timeout)\n        self._session: Optional[aiohttp.ClientSession] = None\n        self._session_lock = asyncio.Lock()\n\n    async def _get_session(self) -> aiohttp.ClientSession:\n        \"\"\"Get or create session with connection pooling\"\"\"\n        if self._session is None or self._session.closed:\n            async with self._session_lock:\n                if self._session is None or self._session.closed:\n                    connector = aiohttp.TCPConnector(\n                        limit=100,  # Total connection pool size\n                        limit_per_host=30,  # Connections per host\n                        force_close=False,\n                        enable_cleanup_closed=True\n                    )\n                    self._session = aiohttp.ClientSession(\n                        connector=connector,\n                        timeout=self.timeout\n                    )\n        return self._session\n\n    @with_metrics\n    async def get(\n        self,\n        endpoint: str,\n        params: Optional[Dict[str, Any]] = None,\n        headers: Optional[Dict[str, str]] = None\n    ) -> Dict[str, Any]:\n        \"\"\"Make GET request with retry logic\"\"\"\n        session = await self._get_session()\n        url = f\"{self.base_url}{endpoint}\"\n\n        async with session.get(\n            url,\n            params=params,\n            headers=headers\n        ) as response:\n            response.raise_for_status()\n            return await response.json()\n\n    @with_metrics\n    async def post(\n        self,\n        endpoint: str,\n        data: Optional[Dict[str, Any]] = None,\n        json: Optional[Dict[str, Any]] = None,\n        headers: Optional[Dict[str, str]] = None\n    ) -> Dict[str, Any]:\n        \"\"\"Make POST request with retry logic\"\"\"\n        session = await self._get_session()\n        url = f\"{self.base_url}{endpoint}\"\n\n        async with session.post(\n            url,\n            data=data,\n            json=json,\n            headers=headers\n        ) as response:\n            response.raise_for_status()\n            return await response.json()\n\n    async def close(self):\n        \"\"\"Close the session\"\"\"\n        if self._session:\n            await self._session.close()\n\n    async def __aenter__(self):\n        return self\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        await self.close()\n```\n\n### 2. Circuit Breaker Pattern\n\n```python\n# patterns\u002Fcircuit_breaker.py\nimport asyncio\nimport time\nfrom enum import Enum\nfrom typing import Callable, Any, Optional\nfrom functools import wraps\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"\n    OPEN = \"open\"\n    HALF_OPEN = \"half_open\"\n\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for fault tolerance\"\"\"\n\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        timeout: int = 60,\n        expected_exception: Exception = Exception\n    ):\n        self.failure_threshold = failure_threshold\n        self.timeout = timeout\n        self.expected_exception = expected_exception\n        self.failure_count = 0\n        self.last_failure_time = None\n        self.state = CircuitState.CLOSED\n\n    def __call__(self, func: Callable) -> Callable:\n        @wraps(func)\n        async def wrapper(*args, **kwargs):\n            if self.state == CircuitState.OPEN:\n                if self._should_attempt_reset():\n                    self.state = CircuitState.HALF_OPEN\n                else:\n                    raise Exception(\"Circuit breaker is OPEN\")\n\n            try:\n                result = await func(*args, **kwargs)\n                if self.state == CircuitState.HALF_OPEN:\n                    self._reset()\n                return result\n            except self.expected_exception as e:\n                self._record_failure()\n                raise\n\n        return wrapper\n\n    def _should_attempt_reset(self) -> bool:\n        return time.time() - self.last_failure_time >= self.timeout\n\n    def _record_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = time.time()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n\n    def _reset(self):\n        self.failure_count = 0\n        self.state = CircuitState.CLOSED\n\n# Usage example\n@circuit_breaker(failure_threshold=3, timeout=30)\nasync def external_api_call():\n    \"\"\"External API call with circuit breaker\"\"\"\n    async with aiohttp.ClientSession() as session:\n        async with session.get(\"https:\u002F\u002Fapi.example.com\") as response:\n            return await response.json()\n```\n\n### 3. Rate Limiting with Redis\n\n```python\n# patterns\u002Frate_limiting.py\nimport asyncio\nimport aioredis\nimport time\nfrom typing import Optional\nfrom fastapi import HTTPException, Request\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nclass RateLimiter:\n    \"\"\"Rate limiter using Redis sliding window\"\"\"\n\n    def __init__(\n        self,\n        redis_url: str,\n        requests_per_minute: int = 100,\n        window_size: int = 60\n    ):\n        self.redis = None\n        self.redis_url = redis_url\n        self.requests_per_minute = requests_per_minute\n        self.window_size = window_size\n\n    async def initialize(self):\n        \"\"\"Initialize Redis connection\"\"\"\n        self.redis = await aioredis.from_url(self.redis_url)\n\n    async def is_allowed(\n        self,\n        key: str,\n        limit: Optional[int] = None,\n        window: Optional[int] = None\n    ) -> bool:\n        \"\"\"Check if request is allowed\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        limit = limit or self.requests_per_minute\n        window = window or self.window_size\n        current_time = time.time()\n\n        # Remove old requests from the sliding window\n        await self.redis.zremrangebyscore(\n            key,\n            0,\n            current_time - window\n        )\n\n        # Count current requests in window\n        current_requests = await self.redis.zcard(key)\n\n        if current_requests >= limit:\n            return False\n\n        # Add current request to window\n        await self.redis.zadd(key, {str(current_time): current_time})\n        await self.redis.expire(key, window)\n\n        return True\n\nclass RateLimitMiddleware(BaseHTTPMiddleware):\n    \"\"\"FastAPI middleware for rate limiting\"\"\"\n\n    def __init__(\n        self,\n        app,\n        redis_url: str,\n        requests_per_minute: int = 100,\n        identifier_func=None\n    ):\n        super().__init__(app)\n        self.limiter = RateLimiter(redis_url, requests_per_minute)\n        self.identifier_func = identifier_func or self._default_identifier\n\n    def _default_identifier(self, request: Request) -> str:\n        \"\"\"Default identifier function\"\"\"\n        # Use IP address as identifier\n        return request.client.host\n\n    async def dispatch(self, request: Request, call_next):\n        identifier = self.identifier_func(request)\n        key = f\"rate_limit:{identifier}:{request.url.path}\"\n\n        if not await self.limiter.is_allowed(key):\n            raise HTTPException(\n                status_code=429,\n                detail=\"Rate limit exceeded\"\n            )\n\n        return await call_next(request)\n```\n\n### 4. API Versioning Strategy\n\n```python\n# patterns\u002Fversioning.py\nfrom enum import Enum\nfrom typing import Optional, Dict, Any, Type\nfrom abc import ABC, abstractmethod\n\nclass APIVersion(str, Enum):\n    V1 = \"v1\"\n    V2 = \"v2\"\n    V3 = \"v3\"\n\nclass APIVersionStrategy(ABC):\n    \"\"\"Base class for API versioning strategies\"\"\"\n\n    @abstractmethod\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        \"\"\"Extract version from request\"\"\"\n        pass\n\nclass HeaderVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from header strategy\"\"\"\n\n    def __init__(self, header_name: str = \"API-Version\"):\n        self.header_name = header_name\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        version = request.headers.get(self.header_name)\n        return APIVersion(version) if version in APIVersion.__members__ else None\n\nclass URLPathVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from URL path strategy\"\"\"\n\n    def __init__(self, prefix: str = \"\u002Fapi\"):\n        self.prefix = prefix\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        path = request.url.path\n        if not path.startswith(self.prefix):\n            return None\n\n        version_part = path[len(self.prefix):].split(\"\u002F\")[1]\n        return APIVersion(version_part) if version_part in APIVersion.__members__ else None\n\nclass QueryParamVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from query parameter strategy\"\"\"\n\n    def __init__(self, param_name: str = \"version\"):\n        self.param_name = param_name\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        version = request.query_params.get(self.param_name)\n        return APIVersion(version) if version in APIVersion.__members__ else None\n\nclass CompositeVersionStrategy(APIVersionStrategy):\n    \"\"\"Composite version strategy that tries multiple strategies\"\"\"\n\n    def __init__(self, strategies: list[APIVersionStrategy]):\n        self.strategies = strategies\n        self.default_version = APIVersion.V1\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        for strategy in self.strategies:\n            version = strategy.get_version_from_request(request)\n            if version:\n                return version\n        return self.default_version\n\n# Version-specific handlers\nclass APIHandlerRegistry:\n    \"\"\"Registry for version-specific API handlers\"\"\"\n\n    def __init__(self):\n        self.handlers: Dict[APIVersion, Dict[str, Any]] = {\n            version: {} for version in APIVersion\n        }\n\n    def register_handler(\n        self,\n        version: APIVersion,\n        endpoint: str,\n        handler: Any\n    ):\n        \"\"\"Register handler for specific version\"\"\"\n        if version not in self.handlers:\n            self.handlers[version] = {}\n        self.handlers[version][endpoint] = handler\n\n    def get_handler(self, version: APIVersion, endpoint: str) -> Optional[Any]:\n        \"\"\"Get handler for version and endpoint\"\"\"\n        return self.handlers.get(version, {}).get(endpoint)\n\n# Usage example\nversion_strategy = CompositeVersionStrategy([\n    HeaderVersionStrategy(),\n    URLPathVersionStrategy(),\n    QueryParamVersionStrategy()\n])\n```\n\n### 5. OpenAPI Documentation Enhancement\n\n```python\n# patterns\u002Fopenapi.py\nfrom typing import Dict, Any, List, Optional\nfrom pydantic import BaseModel, Field\nfrom datetime import datetime\nfrom enum import Enum\n\nclass ErrorSchema(BaseModel):\n    \"\"\"Standard error response schema\"\"\"\n    error: str = Field(..., description=\"Error type\")\n    message: str = Field(..., description=\"Error message\")\n    details: Optional[Dict[str, Any]] = Field(\n        None,\n        description=\"Additional error details\"\n    )\n    timestamp: datetime = Field(\n        default_factory=datetime.utcnow,\n        description=\"Error timestamp\"\n    )\n\nclass PaginationLinks(BaseModel):\n    \"\"\"Pagination links schema\"\"\"\n    first: Optional[str] = Field(None, description=\"First page link\")\n    last: Optional[str] = Field(None, description=\"Last page link\")\n    next: Optional[str] = Field(None, description=\"Next page link\")\n    prev: Optional[str] = Field(None, description=\"Previous page link\")\n\nclass PaginationMeta(BaseModel):\n    \"\"\"Pagination metadata schema\"\"\"\n    total: int = Field(..., description=\"Total number of items\")\n    page: int = Field(..., description=\"Current page number\")\n    per_page: int = Field(..., description=\"Items per page\")\n    pages: int = Field(..., description=\"Total number of pages\")\n\nclass PaginatedResponse(BaseModel):\n    \"\"\"Generic paginated response schema\"\"\"\n    data: List[Any] = Field(..., description=\"Response data\")\n    meta: PaginationMeta = Field(..., description=\"Pagination metadata\")\n    links: PaginationLinks = Field(..., description=\"Pagination links\")\n\n# Enhanced OpenAPI configuration\nOPENAPI_CONFIG = {\n    \"title\": \"Modern API\",\n    \"description\": \"A modern REST API with async patterns\",\n    \"version\": \"1.0.0\",\n    \"docs_url\": \"\u002Fdocs\",\n    \"redoc_url\": \"\u002Fredoc\",\n    \"openapi_url\": \"\u002Fopenapi.json\",\n    \"servers\": [\n        {\n            \"url\": \"https:\u002F\u002Fapi.example.com\u002Fv1\",\n            \"description\": \"Production server\"\n        },\n        {\n            \"url\": \"https:\u002F\u002Fstaging-api.example.com\u002Fv1\",\n            \"description\": \"Staging server\"\n        }\n    ],\n    \"components\": {\n        \"schemas\": {\n            \"Error\": ErrorSchema.model_json_schema(),\n            \"PaginatedResponse\": PaginatedResponse.model_json_schema()\n        },\n        \"responses\": {\n            \"ValidationError\": {\n                \"description\": \"Validation error\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"UnauthorizedError\": {\n                \"description\": \"Unauthorized error\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"NotFoundError\": {\n                \"description\": \"Resource not found\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"RateLimitError\": {\n                \"description\": \"Rate limit exceeded\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n### 6. Testing Patterns for APIs\n\n```python\n# patterns\u002Ftesting.py\nimport pytest\nimport asyncio\nfrom typing import AsyncGenerator\nimport httpx\nfrom fastapi.testclient import TestClient\nfrom unittest.mock import AsyncMock, patch\n\nclass AsyncAPITestCase:\n    \"\"\"Base class for async API tests\"\"\"\n\n    @pytest.fixture(scope=\"class\")\n    async def async_client(self) -> AsyncGenerator[httpx.AsyncClient, None]:\n        \"\"\"Create async test client\"\"\"\n        async with httpx.AsyncClient(\n            app=self.app,\n            base_url=\"http:\u002F\u002Ftest\"\n        ) as client:\n            yield client\n\n    @pytest.fixture\n    def mock_external_service(self):\n        \"\"\"Mock external service\"\"\"\n        with patch(\"external_api_client.ExternalAPIClient\") as mock:\n            client = mock.return_value\n            client.get.return_value = {\"status\": \"ok\"}\n            yield client\n\n# Example test cases\n@pytest.mark.asyncio\nclass TestUserAPI(AsyncAPITestCase):\n    \"\"\"Test user API endpoints\"\"\"\n\n    async def test_create_user(self, async_client: httpx.AsyncClient):\n        \"\"\"Test user creation\"\"\"\n        user_data = {\n            \"email\": \"test@example.com\",\n            \"username\": \"testuser\",\n            \"password\": \"securepassword123\"\n        }\n\n        response = await async_client.post(\n            \"\u002Fapi\u002Fusers\",\n            json=user_data\n        )\n\n        assert response.status_code == 201\n        data = response.json()\n        assert data[\"email\"] == user_data[\"email\"]\n        assert data[\"username\"] == user_data[\"username\"]\n        assert \"password\" not in data\n\n    async def test_get_user(self, async_client: httpx.AsyncClient):\n        \"\"\"Test get user\"\"\"\n        # First create a user\n        create_response = await async_client.post(\n            \"\u002Fapi\u002Fusers\",\n            json={\n                \"email\": \"test2@example.com\",\n                \"username\": \"testuser2\",\n                \"password\": \"securepassword123\"\n            }\n        )\n        user_id = create_response.json()[\"id\"]\n\n        # Get user\n        response = await async_client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert response.status_code == 200\n        data = response.json()\n        assert data[\"id\"] == user_id\n\n    async def test_list_users_with_pagination(\n        self,\n        async_client: httpx.AsyncClient\n    ):\n        \"\"\"Test user listing with pagination\"\"\"\n        response = await async_client.get(\"\u002Fapi\u002Fusers?page=1&per_page=10\")\n        assert response.status_code == 200\n        data = response.json()\n        assert \"data\" in data\n        assert \"meta\" in data\n        assert \"links\" in data\n        assert data[\"meta\"][\"page\"] == 1\n        assert data[\"meta\"][\"per_page\"] == 10\n\n    async def test_rate_limiting(\n        self,\n        async_client: httpx.AsyncClient\n    ):\n        \"\"\"Test rate limiting\"\"\"\n        # Make multiple requests quickly\n        responses = []\n        for _ in range(150):  # Assuming rate limit is 100\u002Fminute\n            response = await async_client.get(\"\u002Fapi\u002Fusers\")\n            responses.append(response)\n\n        # Check if rate limiting kicked in\n        rate_limited = any(\n            r.status_code == 429 for r in responses\n        )\n        assert rate_limited\n\n# Integration tests\n@pytest.mark.asyncio\nasync def test_full_user_flow():\n    \"\"\"Test complete user workflow\"\"\"\n    async with httpx.AsyncClient(\n        app=app,\n        base_url=\"http:\u002F\u002Ftest\"\n    ) as client:\n\n        # Create user\n        user_data = {\n            \"email\": \"flowtest@example.com\",\n            \"username\": \"flowtest\",\n            \"password\": \"securepassword123\"\n        }\n        create_resp = await client.post(\"\u002Fapi\u002Fusers\", json=user_data)\n        assert create_resp.status_code == 201\n        user = create_resp.json()\n        user_id = user[\"id\"]\n\n        # Get user\n        get_resp = await client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert get_resp.status_code == 200\n        assert get_resp.json()[\"id\"] == user_id\n\n        # Update user\n        update_data = {\"username\": \"updateduser\"}\n        update_resp = await client.patch(\n            f\"\u002Fapi\u002Fusers\u002F{user_id}\",\n            json=update_data\n        )\n        assert update_resp.status_code == 200\n        assert update_resp.json()[\"username\"] == \"updateduser\"\n\n        # Delete user\n        delete_resp = await client.delete(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert delete_resp.status_code == 204\n\n        # Verify user is deleted\n        get_resp = await client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert get_resp.status_code == 404\n```\n\n### 7. Performance Optimization Patterns\n\n```python\n# patterns\u002Fperformance.py\nimport asyncio\nimport asyncio.cache\nimport aioredis\nfrom typing import Any, Optional, Callable\nfrom functools import wraps\nimport hashlib\nimport json\nimport pickle\n\nclass ResponseCache:\n    \"\"\"Response caching with Redis\"\"\"\n\n    def __init__(self, redis_url: str, default_ttl: int = 300):\n        self.redis = None\n        self.redis_url = redis_url\n        self.default_ttl = default_ttl\n\n    async def initialize(self):\n        \"\"\"Initialize Redis connection\"\"\"\n        self.redis = await aioredis.from_url(self.redis_url)\n\n    def _make_cache_key(self, prefix: str, *args, **kwargs) -> str:\n        \"\"\"Generate cache key from arguments\"\"\"\n        key_data = {\n            \"args\": args,\n            \"kwargs\": kwargs\n        }\n        key_str = json.dumps(key_data, sort_keys=True, default=str)\n        key_hash = hashlib.sha256(key_str.encode()).hexdigest()\n        return f\"{prefix}:{key_hash}\"\n\n    async def get(self, key: str) -> Optional[Any]:\n        \"\"\"Get cached value\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        cached = await self.redis.get(key)\n        if cached:\n            return pickle.loads(cached)\n        return None\n\n    async def set(\n        self,\n        key: str,\n        value: Any,\n        ttl: Optional[int] = None\n    ):\n        \"\"\"Set cached value\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        ttl = ttl or self.default_ttl\n        serialized = pickle.dumps(value)\n        await self.redis.setex(key, ttl, serialized)\n\n    async def delete(self, key: str):\n        \"\"\"Delete cached value\"\"\"\n        if self.redis:\n            await self.redis.delete(key)\n\ndef cache_response(\n    prefix: str,\n    ttl: Optional[int] = None,\n    cache: Optional[ResponseCache] = None\n):\n    \"\"\"Decorator to cache response\"\"\"\n    def decorator(func: Callable) -> Callable:\n        @wraps(func)\n        async def wrapper(*args, **kwargs):\n            cache_instance = cache or ResponseCache(\"redis:\u002F\u002Flocalhost\")\n\n            # Generate cache key\n            cache_key = cache_instance._make_cache_key(prefix, *args, **kwargs)\n\n            # Try to get from cache\n            cached_result = await cache_instance.get(cache_key)\n            if cached_result is not None:\n                return cached_result\n\n            # Execute function\n            result = await func(*args, **kwargs)\n\n            # Cache result\n            await cache_instance.set(cache_key, result, ttl)\n\n            return result\n\n        return wrapper\n    return decorator\n\n# Usage example\n@cache_response(prefix=\"user_data\", ttl=300)\nasync def get_user_data(user_id: int) -> Dict[str, Any]:\n    \"\"\"Get user data with caching\"\"\"\n    # Expensive database operation or API call\n    await asyncio.sleep(1)  # Simulate slow operation\n    return {\"id\": user_id, \"name\": \"John Doe\", \"email\": \"john@example.com\"}\n\n# Batch processing for performance\nclass BatchProcessor:\n    \"\"\"Batch processor for optimizing multiple operations\"\"\"\n\n    def __init__(self, batch_size: int = 100, flush_interval: int = 5):\n        self.batch_size = batch_size\n        self.flush_interval = flush_interval\n        self.queue = asyncio.Queue()\n        self.processing = False\n\n    async def add(self, item: Any):\n        \"\"\"Add item to batch queue\"\"\"\n        await self.queue.put(item)\n        if not self.processing:\n            self.processing = True\n            asyncio.create_task(self._process_batch())\n\n    async def _process_batch(self):\n        \"\"\"Process items in batches\"\"\"\n        while True:\n            batch = []\n\n            # Collect batch items\n            try:\n                deadline = asyncio.get_event_loop().time() + self.flush_interval\n\n                while len(batch) \u003C self.batch_size:\n                    try:\n                        timeout = max(0, deadline - asyncio.get_event_loop().time())\n                        item = await asyncio.wait_for(\n                            self.queue.get(),\n                            timeout=timeout\n                        )\n                        batch.append(item)\n                    except asyncio.TimeoutError:\n                        break\n\n                if batch:\n                    await self._process_batch_items(batch)\n\n            except Exception as e:\n                print(f\"Error processing batch: {e}\")\n                continue\n\n    async def _process_batch_items(self, batch: list[Any]):\n        \"\"\"Process a batch of items\"\"\"\n        # Override in subclasses\n        # Example: batch database insert, batch API calls, etc.\n        print(f\"Processing batch of {len(batch)} items\")\n```\n\n### 8. Production Configuration Checklist\n\n```yaml\n# api\u002Fproduction_checklist.yaml\nperformance:\n  async_patterns:\n    connection_pooling: true\n    max_connections: 100\n    connection_timeout: 30\n    keep_alive: true\n\n  caching:\n    redis_cache: true\n    default_ttl: 300\n    cache_headers: true\n\n  compression:\n    gzip: true\n    level: 6\n    threshold: 1024\n\n  rate_limiting:\n    enabled: true\n    default_limit: 100\u002Fminute\n    burst_limit: 200\n    sliding_window: true\n\nsecurity:\n  authentication:\n    jwt_validation: true\n    token_refresh: true\n    revoke_tokens: true\n\n  authorization:\n    rbac: true\n    rate_limit_by_role: true\n\n  validation:\n    input_validation: true\n    sql_injection_protection: true\n    xss_protection: true\n\n  headers:\n    security_headers: true\n    cors: true\n    csrf_protection: true\n\nmonitoring:\n  metrics:\n    prometheus: true\n    request_duration: true\n    error_rate: true\n    throughput: true\n\n  logging:\n    structured_logging: true\n    correlation_ids: true\n    error_tracking: true\n\n  health_checks:\n    liveness_probe: true\n    readiness_probe: true\n    dependency_checks: true\n\ndocumentation:\n  openapi:\n    auto_generation: true\n    examples: true\n    schemas: true\n\n  versioning:\n    strategy: \"header_path_query\"\n    deprecation_warnings: true\n    backward_compatibility: true\n\n  testing:\n    unit_tests: true\n    integration_tests: true\n    performance_tests: true\n    contract_tests: true\n```\n\nThis comprehensive API development skill provides modern patterns for building high-performance APIs in 2025, including async\u002Fawait patterns, circuit breakers, rate limiting, versioning strategies, comprehensive testing, and production optimization techniques that work across different frameworks.","# API Development Patterns & Best Practices\n\nThis skill provides comprehensive patterns for building modern APIs in 2025, focusing on async\u002Fawait patterns, performance optimization, security, testing, and production-ready configurations that work across different frameworks and languages.\n\n## When to Use This Skill\n\nUse this skill when you need to:\n- Design RESTful or GraphQL APIs\n- Implement async\u002Fawait patterns for high performance\n- Add middleware for authentication, logging, and validation\n- Handle errors gracefully with proper HTTP status codes\n- Implement rate limiting and throttling\n- Generate OpenAPI\u002FSwagger documentation\n- Set up comprehensive testing strategies\n- Optimize API performance with caching and connection pooling\n- Implement API versioning and backward compatibility\n- Set up monitoring and observability\n\n## Core API Design Principles\n\n### 1. Async\u002FAwait Patterns for Performance\n\n```python\n# patterns\u002Fasync_patterns.py\nimport asyncio\nimport aiohttp\nimport aioredis\nfrom typing import AsyncGenerator, Optional, List, Dict, Any\nfrom contextlib import asynccontextmanager\nfrom dataclasses import dataclass\nfrom functools import wraps\nimport time\n\n@dataclass\nclass RequestMetrics:\n    \"\"\"Request metrics for monitoring\"\"\"\n    duration: float\n    status_code: int\n    endpoint: str\n    method: str\n    user_id: Optional[str] = None\n\ndef with_metrics(func):\n    \"\"\"Decorator to add request metrics\"\"\"\n    @wraps(func)\n    async def wrapper(*args, **kwargs):\n        start_time = time.time()\n        status_code = 200\n        endpoint = func.__name__\n        method = kwargs.get('method', 'GET')\n\n        try:\n            result = await func(*args, **kwargs)\n            if hasattr(result, 'status_code'):\n                status_code = result.status_code\n            return result\n        except Exception as e:\n            status_code = getattr(e, 'status_code', 500)\n            raise\n        finally:\n            duration = time.time() - start_time\n            metrics = RequestMetrics(\n                duration=duration,\n                status_code=status_code,\n                endpoint=endpoint,\n                method=method\n            )\n            # Send metrics to monitoring system\n            await send_metrics(metrics)\n\n    return wrapper\n\nasync def send_metrics(metrics: RequestMetrics):\n    \"\"\"Send metrics to monitoring system\"\"\"\n    # Implementation depends on your monitoring system\n    # Example: Prometheus, Datadog, or custom analytics\n    pass\n\nclass AsyncAPIClient:\n    \"\"\"Generic async API client with connection pooling\"\"\"\n\n    def __init__(self, base_url: str, timeout: int = 30):\n        self.base_url = base_url\n        self.timeout = aiohttp.ClientTimeout(total=timeout)\n        self._session: Optional[aiohttp.ClientSession] = None\n        self._session_lock = asyncio.Lock()\n\n    async def _get_session(self) -> aiohttp.ClientSession:\n        \"\"\"Get or create session with connection pooling\"\"\"\n        if self._session is None or self._session.closed:\n            async with self._session_lock:\n                if self._session is None or self._session.closed:\n                    connector = aiohttp.TCPConnector(\n                        limit=100,  # Total connection pool size\n                        limit_per_host=30,  # Connections per host\n                        force_close=False,\n                        enable_cleanup_closed=True\n                    )\n                    self._session = aiohttp.ClientSession(\n                        connector=connector,\n                        timeout=self.timeout\n                    )\n        return self._session\n\n    @with_metrics\n    async def get(\n        self,\n        endpoint: str,\n        params: Optional[Dict[str, Any]] = None,\n        headers: Optional[Dict[str, str]] = None\n    ) -> Dict[str, Any]:\n        \"\"\"Make GET request with retry logic\"\"\"\n        session = await self._get_session()\n        url = f\"{self.base_url}{endpoint}\"\n\n        async with session.get(\n            url,\n            params=params,\n            headers=headers\n        ) as response:\n            response.raise_for_status()\n            return await response.json()\n\n    @with_metrics\n    async def post(\n        self,\n        endpoint: str,\n        data: Optional[Dict[str, Any]] = None,\n        json: Optional[Dict[str, Any]] = None,\n        headers: Optional[Dict[str, str]] = None\n    ) -> Dict[str, Any]:\n        \"\"\"Make POST request with retry logic\"\"\"\n        session = await self._get_session()\n        url = f\"{self.base_url}{endpoint}\"\n\n        async with session.post(\n            url,\n            data=data,\n            json=json,\n            headers=headers\n        ) as response:\n            response.raise_for_status()\n            return await response.json()\n\n    async def close(self):\n        \"\"\"Close the session\"\"\"\n        if self._session:\n            await self._session.close()\n\n    async def __aenter__(self):\n        return self\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        await self.close()\n```\n\n### 2. Circuit Breaker Pattern\n\n```python\n# patterns\u002Fcircuit_breaker.py\nimport asyncio\nimport time\nfrom enum import Enum\nfrom typing import Callable, Any, Optional\nfrom functools import wraps\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"\n    OPEN = \"open\"\n    HALF_OPEN = \"half_open\"\n\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for fault tolerance\"\"\"\n\n    def __init__(\n        self,\n        failure_threshold: int = 5,\n        timeout: int = 60,\n        expected_exception: Exception = Exception\n    ):\n        self.failure_threshold = failure_threshold\n        self.timeout = timeout\n        self.expected_exception = expected_exception\n        self.failure_count = 0\n        self.last_failure_time = None\n        self.state = CircuitState.CLOSED\n\n    def __call__(self, func: Callable) -> Callable:\n        @wraps(func)\n        async def wrapper(*args, **kwargs):\n            if self.state == CircuitState.OPEN:\n                if self._should_attempt_reset():\n                    self.state = CircuitState.HALF_OPEN\n                else:\n                    raise Exception(\"Circuit breaker is OPEN\")\n\n            try:\n                result = await func(*args, **kwargs)\n                if self.state == CircuitState.HALF_OPEN:\n                    self._reset()\n                return result\n            except self.expected_exception as e:\n                self._record_failure()\n                raise\n\n        return wrapper\n\n    def _should_attempt_reset(self) -> bool:\n        return time.time() - self.last_failure_time >= self.timeout\n\n    def _record_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = time.time()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n\n    def _reset(self):\n        self.failure_count = 0\n        self.state = CircuitState.CLOSED\n\n# Usage example\n@circuit_breaker(failure_threshold=3, timeout=30)\nasync def external_api_call():\n    \"\"\"External API call with circuit breaker\"\"\"\n    async with aiohttp.ClientSession() as session:\n        async with session.get(\"https:\u002F\u002Fapi.example.com\") as response:\n            return await response.json()\n```\n\n### 3. Rate Limiting with Redis\n\n```python\n# patterns\u002Frate_limiting.py\nimport asyncio\nimport aioredis\nimport time\nfrom typing import Optional\nfrom fastapi import HTTPException, Request\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nclass RateLimiter:\n    \"\"\"Rate limiter using Redis sliding window\"\"\"\n\n    def __init__(\n        self,\n        redis_url: str,\n        requests_per_minute: int = 100,\n        window_size: int = 60\n    ):\n        self.redis = None\n        self.redis_url = redis_url\n        self.requests_per_minute = requests_per_minute\n        self.window_size = window_size\n\n    async def initialize(self):\n        \"\"\"Initialize Redis connection\"\"\"\n        self.redis = await aioredis.from_url(self.redis_url)\n\n    async def is_allowed(\n        self,\n        key: str,\n        limit: Optional[int] = None,\n        window: Optional[int] = None\n    ) -> bool:\n        \"\"\"Check if request is allowed\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        limit = limit or self.requests_per_minute\n        window = window or self.window_size\n        current_time = time.time()\n\n        # Remove old requests from the sliding window\n        await self.redis.zremrangebyscore(\n            key,\n            0,\n            current_time - window\n        )\n\n        # Count current requests in window\n        current_requests = await self.redis.zcard(key)\n\n        if current_requests >= limit:\n            return False\n\n        # Add current request to window\n        await self.redis.zadd(key, {str(current_time): current_time})\n        await self.redis.expire(key, window)\n\n        return True\n\nclass RateLimitMiddleware(BaseHTTPMiddleware):\n    \"\"\"FastAPI middleware for rate limiting\"\"\"\n\n    def __init__(\n        self,\n        app,\n        redis_url: str,\n        requests_per_minute: int = 100,\n        identifier_func=None\n    ):\n        super().__init__(app)\n        self.limiter = RateLimiter(redis_url, requests_per_minute)\n        self.identifier_func = identifier_func or self._default_identifier\n\n    def _default_identifier(self, request: Request) -> str:\n        \"\"\"Default identifier function\"\"\"\n        # Use IP address as identifier\n        return request.client.host\n\n    async def dispatch(self, request: Request, call_next):\n        identifier = self.identifier_func(request)\n        key = f\"rate_limit:{identifier}:{request.url.path}\"\n\n        if not await self.limiter.is_allowed(key):\n            raise HTTPException(\n                status_code=429,\n                detail=\"Rate limit exceeded\"\n            )\n\n        return await call_next(request)\n```\n\n### 4. API Versioning Strategy\n\n```python\n# patterns\u002Fversioning.py\nfrom enum import Enum\nfrom typing import Optional, Dict, Any, Type\nfrom abc import ABC, abstractmethod\n\nclass APIVersion(str, Enum):\n    V1 = \"v1\"\n    V2 = \"v2\"\n    V3 = \"v3\"\n\nclass APIVersionStrategy(ABC):\n    \"\"\"Base class for API versioning strategies\"\"\"\n\n    @abstractmethod\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        \"\"\"Extract version from request\"\"\"\n        pass\n\nclass HeaderVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from header strategy\"\"\"\n\n    def __init__(self, header_name: str = \"API-Version\"):\n        self.header_name = header_name\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        version = request.headers.get(self.header_name)\n        return APIVersion(version) if version in APIVersion.__members__ else None\n\nclass URLPathVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from URL path strategy\"\"\"\n\n    def __init__(self, prefix: str = \"\u002Fapi\"):\n        self.prefix = prefix\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        path = request.url.path\n        if not path.startswith(self.prefix):\n            return None\n\n        version_part = path[len(self.prefix):].split(\"\u002F\")[1]\n        return APIVersion(version_part) if version_part in APIVersion.__members__ else None\n\nclass QueryParamVersionStrategy(APIVersionStrategy):\n    \"\"\"Version from query parameter strategy\"\"\"\n\n    def __init__(self, param_name: str = \"version\"):\n        self.param_name = param_name\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        version = request.query_params.get(self.param_name)\n        return APIVersion(version) if version in APIVersion.__members__ else None\n\nclass CompositeVersionStrategy(APIVersionStrategy):\n    \"\"\"Composite version strategy that tries multiple strategies\"\"\"\n\n    def __init__(self, strategies: list[APIVersionStrategy]):\n        self.strategies = strategies\n        self.default_version = APIVersion.V1\n\n    def get_version_from_request(self, request) -> Optional[APIVersion]:\n        for strategy in self.strategies:\n            version = strategy.get_version_from_request(request)\n            if version:\n                return version\n        return self.default_version\n\n# Version-specific handlers\nclass APIHandlerRegistry:\n    \"\"\"Registry for version-specific API handlers\"\"\"\n\n    def __init__(self):\n        self.handlers: Dict[APIVersion, Dict[str, Any]] = {\n            version: {} for version in APIVersion\n        }\n\n    def register_handler(\n        self,\n        version: APIVersion,\n        endpoint: str,\n        handler: Any\n    ):\n        \"\"\"Register handler for specific version\"\"\"\n        if version not in self.handlers:\n            self.handlers[version] = {}\n        self.handlers[version][endpoint] = handler\n\n    def get_handler(self, version: APIVersion, endpoint: str) -> Optional[Any]:\n        \"\"\"Get handler for version and endpoint\"\"\"\n        return self.handlers.get(version, {}).get(endpoint)\n\n# Usage example\nversion_strategy = CompositeVersionStrategy([\n    HeaderVersionStrategy(),\n    URLPathVersionStrategy(),\n    QueryParamVersionStrategy()\n])\n```\n\n### 5. OpenAPI Documentation Enhancement\n\n```python\n# patterns\u002Fopenapi.py\nfrom typing import Dict, Any, List, Optional\nfrom pydantic import BaseModel, Field\nfrom datetime import datetime\nfrom enum import Enum\n\nclass ErrorSchema(BaseModel):\n    \"\"\"Standard error response schema\"\"\"\n    error: str = Field(..., description=\"Error type\")\n    message: str = Field(..., description=\"Error message\")\n    details: Optional[Dict[str, Any]] = Field(\n        None,\n        description=\"Additional error details\"\n    )\n    timestamp: datetime = Field(\n        default_factory=datetime.utcnow,\n        description=\"Error timestamp\"\n    )\n\nclass PaginationLinks(BaseModel):\n    \"\"\"Pagination links schema\"\"\"\n    first: Optional[str] = Field(None, description=\"First page link\")\n    last: Optional[str] = Field(None, description=\"Last page link\")\n    next: Optional[str] = Field(None, description=\"Next page link\")\n    prev: Optional[str] = Field(None, description=\"Previous page link\")\n\nclass PaginationMeta(BaseModel):\n    \"\"\"Pagination metadata schema\"\"\"\n    total: int = Field(..., description=\"Total number of items\")\n    page: int = Field(..., description=\"Current page number\")\n    per_page: int = Field(..., description=\"Items per page\")\n    pages: int = Field(..., description=\"Total number of pages\")\n\nclass PaginatedResponse(BaseModel):\n    \"\"\"Generic paginated response schema\"\"\"\n    data: List[Any] = Field(..., description=\"Response data\")\n    meta: PaginationMeta = Field(..., description=\"Pagination metadata\")\n    links: PaginationLinks = Field(..., description=\"Pagination links\")\n\n# Enhanced OpenAPI configuration\nOPENAPI_CONFIG = {\n    \"title\": \"Modern API\",\n    \"description\": \"A modern REST API with async patterns\",\n    \"version\": \"1.0.0\",\n    \"docs_url\": \"\u002Fdocs\",\n    \"redoc_url\": \"\u002Fredoc\",\n    \"openapi_url\": \"\u002Fopenapi.json\",\n    \"servers\": [\n        {\n            \"url\": \"https:\u002F\u002Fapi.example.com\u002Fv1\",\n            \"description\": \"Production server\"\n        },\n        {\n            \"url\": \"https:\u002F\u002Fstaging-api.example.com\u002Fv1\",\n            \"description\": \"Staging server\"\n        }\n    ],\n    \"components\": {\n        \"schemas\": {\n            \"Error\": ErrorSchema.model_json_schema(),\n            \"PaginatedResponse\": PaginatedResponse.model_json_schema()\n        },\n        \"responses\": {\n            \"ValidationError\": {\n                \"description\": \"Validation error\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"UnauthorizedError\": {\n                \"description\": \"Unauthorized error\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"NotFoundError\": {\n                \"description\": \"Resource not found\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            },\n            \"RateLimitError\": {\n                \"description\": \"Rate limit exceeded\",\n                \"content\": {\n                    \"application\u002Fjson\": {\n                        \"schema\": ErrorSchema.model_json_schema()\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n### 6. Testing Patterns for APIs\n\n```python\n# patterns\u002Ftesting.py\nimport pytest\nimport asyncio\nfrom typing import AsyncGenerator\nimport httpx\nfrom fastapi.testclient import TestClient\nfrom unittest.mock import AsyncMock, patch\n\nclass AsyncAPITestCase:\n    \"\"\"Base class for async API tests\"\"\"\n\n    @pytest.fixture(scope=\"class\")\n    async def async_client(self) -> AsyncGenerator[httpx.AsyncClient, None]:\n        \"\"\"Create async test client\"\"\"\n        async with httpx.AsyncClient(\n            app=self.app,\n            base_url=\"http:\u002F\u002Ftest\"\n        ) as client:\n            yield client\n\n    @pytest.fixture\n    def mock_external_service(self):\n        \"\"\"Mock external service\"\"\"\n        with patch(\"external_api_client.ExternalAPIClient\") as mock:\n            client = mock.return_value\n            client.get.return_value = {\"status\": \"ok\"}\n            yield client\n\n# Example test cases\n@pytest.mark.asyncio\nclass TestUserAPI(AsyncAPITestCase):\n    \"\"\"Test user API endpoints\"\"\"\n\n    async def test_create_user(self, async_client: httpx.AsyncClient):\n        \"\"\"Test user creation\"\"\"\n        user_data = {\n            \"email\": \"test@example.com\",\n            \"username\": \"testuser\",\n            \"password\": \"securepassword123\"\n        }\n\n        response = await async_client.post(\n            \"\u002Fapi\u002Fusers\",\n            json=user_data\n        )\n\n        assert response.status_code == 201\n        data = response.json()\n        assert data[\"email\"] == user_data[\"email\"]\n        assert data[\"username\"] == user_data[\"username\"]\n        assert \"password\" not in data\n\n    async def test_get_user(self, async_client: httpx.AsyncClient):\n        \"\"\"Test get user\"\"\"\n        # First create a user\n        create_response = await async_client.post(\n            \"\u002Fapi\u002Fusers\",\n            json={\n                \"email\": \"test2@example.com\",\n                \"username\": \"testuser2\",\n                \"password\": \"securepassword123\"\n            }\n        )\n        user_id = create_response.json()[\"id\"]\n\n        # Get user\n        response = await async_client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert response.status_code == 200\n        data = response.json()\n        assert data[\"id\"] == user_id\n\n    async def test_list_users_with_pagination(\n        self,\n        async_client: httpx.AsyncClient\n    ):\n        \"\"\"Test user listing with pagination\"\"\"\n        response = await async_client.get(\"\u002Fapi\u002Fusers?page=1&per_page=10\")\n        assert response.status_code == 200\n        data = response.json()\n        assert \"data\" in data\n        assert \"meta\" in data\n        assert \"links\" in data\n        assert data[\"meta\"][\"page\"] == 1\n        assert data[\"meta\"][\"per_page\"] == 10\n\n    async def test_rate_limiting(\n        self,\n        async_client: httpx.AsyncClient\n    ):\n        \"\"\"Test rate limiting\"\"\"\n        # Make multiple requests quickly\n        responses = []\n        for _ in range(150):  # Assuming rate limit is 100\u002Fminute\n            response = await async_client.get(\"\u002Fapi\u002Fusers\")\n            responses.append(response)\n\n        # Check if rate limiting kicked in\n        rate_limited = any(\n            r.status_code == 429 for r in responses\n        )\n        assert rate_limited\n\n# Integration tests\n@pytest.mark.asyncio\nasync def test_full_user_flow():\n    \"\"\"Test complete user workflow\"\"\"\n    async with httpx.AsyncClient(\n        app=app,\n        base_url=\"http:\u002F\u002Ftest\"\n    ) as client:\n\n        # Create user\n        user_data = {\n            \"email\": \"flowtest@example.com\",\n            \"username\": \"flowtest\",\n            \"password\": \"securepassword123\"\n        }\n        create_resp = await client.post(\"\u002Fapi\u002Fusers\", json=user_data)\n        assert create_resp.status_code == 201\n        user = create_resp.json()\n        user_id = user[\"id\"]\n\n        # Get user\n        get_resp = await client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert get_resp.status_code == 200\n        assert get_resp.json()[\"id\"] == user_id\n\n        # Update user\n        update_data = {\"username\": \"updateduser\"}\n        update_resp = await client.patch(\n            f\"\u002Fapi\u002Fusers\u002F{user_id}\",\n            json=update_data\n        )\n        assert update_resp.status_code == 200\n        assert update_resp.json()[\"username\"] == \"updateduser\"\n\n        # Delete user\n        delete_resp = await client.delete(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert delete_resp.status_code == 204\n\n        # Verify user is deleted\n        get_resp = await client.get(f\"\u002Fapi\u002Fusers\u002F{user_id}\")\n        assert get_resp.status_code == 404\n```\n\n### 7. Performance Optimization Patterns\n\n```python\n# patterns\u002Fperformance.py\nimport asyncio\nimport asyncio.cache\nimport aioredis\nfrom typing import Any, Optional, Callable\nfrom functools import wraps\nimport hashlib\nimport json\nimport pickle\n\nclass ResponseCache:\n    \"\"\"Response caching with Redis\"\"\"\n\n    def __init__(self, redis_url: str, default_ttl: int = 300):\n        self.redis = None\n        self.redis_url = redis_url\n        self.default_ttl = default_ttl\n\n    async def initialize(self):\n        \"\"\"Initialize Redis connection\"\"\"\n        self.redis = await aioredis.from_url(self.redis_url)\n\n    def _make_cache_key(self, prefix: str, *args, **kwargs) -> str:\n        \"\"\"Generate cache key from arguments\"\"\"\n        key_data = {\n            \"args\": args,\n            \"kwargs\": kwargs\n        }\n        key_str = json.dumps(key_data, sort_keys=True, default=str)\n        key_hash = hashlib.sha256(key_str.encode()).hexdigest()\n        return f\"{prefix}:{key_hash}\"\n\n    async def get(self, key: str) -> Optional[Any]:\n        \"\"\"Get cached value\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        cached = await self.redis.get(key)\n        if cached:\n            return pickle.loads(cached)\n        return None\n\n    async def set(\n        self,\n        key: str,\n        value: Any,\n        ttl: Optional[int] = None\n    ):\n        \"\"\"Set cached value\"\"\"\n        if not self.redis:\n            await self.initialize()\n\n        ttl = ttl or self.default_ttl\n        serialized = pickle.dumps(value)\n        await self.redis.setex(key, ttl, serialized)\n\n    async def delete(self, key: str):\n        \"\"\"Delete cached value\"\"\"\n        if self.redis:\n            await self.redis.delete(key)\n\ndef cache_response(\n    prefix: str,\n    ttl: Optional[int] = None,\n    cache: Optional[ResponseCache] = None\n):\n    \"\"\"Decorator to cache response\"\"\"\n    def decorator(func: Callable) -> Callable:\n        @wraps(func)\n        async def wrapper(*args, **kwargs):\n            cache_instance = cache or ResponseCache(\"redis:\u002F\u002Flocalhost\")\n\n            # Generate cache key\n            cache_key = cache_instance._make_cache_key(prefix, *args, **kwargs)\n\n            # Try to get from cache\n            cached_result = await cache_instance.get(cache_key)\n            if cached_result is not None:\n                return cached_result\n\n            # Execute function\n            result = await func(*args, **kwargs)\n\n            # Cache result\n            await cache_instance.set(cache_key, result, ttl)\n\n            return result\n\n        return wrapper\n    return decorator\n\n# Usage example\n@cache_response(prefix=\"user_data\", ttl=300)\nasync def get_user_data(user_id: int) -> Dict[str, Any]:\n    \"\"\"Get user data with caching\"\"\"\n    # Expensive database operation or API call\n    await asyncio.sleep(1)  # Simulate slow operation\n    return {\"id\": user_id, \"name\": \"John Doe\", \"email\": \"john@example.com\"}\n\n# Batch processing for performance\nclass BatchProcessor:\n    \"\"\"Batch processor for optimizing multiple operations\"\"\"\n\n    def __init__(self, batch_size: int = 100, flush_interval: int = 5):\n        self.batch_size = batch_size\n        self.flush_interval = flush_interval\n        self.queue = asyncio.Queue()\n        self.processing = False\n\n    async def add(self, item: Any):\n        \"\"\"Add item to batch queue\"\"\"\n        await self.queue.put(item)\n        if not self.processing:\n            self.processing = True\n            asyncio.create_task(self._process_batch())\n\n    async def _process_batch(self):\n        \"\"\"Process items in batches\"\"\"\n        while True:\n            batch = []\n\n            # Collect batch items\n            try:\n                deadline = asyncio.get_event_loop().time() + self.flush_interval\n\n                while len(batch) \u003C self.batch_size:\n                    try:\n                        timeout = max(0, deadline - asyncio.get_event_loop().time())\n                        item = await asyncio.wait_for(\n                            self.queue.get(),\n                            timeout=timeout\n                        )\n                        batch.append(item)\n                    except asyncio.TimeoutError:\n                        break\n\n                if batch:\n                    await self._process_batch_items(batch)\n\n            except Exception as e:\n                print(f\"Error processing batch: {e}\")\n                continue\n\n    async def _process_batch_items(self, batch: list[Any]):\n        \"\"\"Process a batch of items\"\"\"\n        # Override in subclasses\n        # Example: batch database insert, batch API calls, etc.\n        print(f\"Processing batch of {len(batch)} items\")\n```\n\n### 8. Production Configuration Checklist\n\n```yaml\n# api\u002Fproduction_checklist.yaml\nperformance:\n  async_patterns:\n    connection_pooling: true\n    max_connections: 100\n    connection_timeout: 30\n    keep_alive: true\n\n  caching:\n    redis_cache: true\n    default_ttl: 300\n    cache_headers: true\n\n  compression:\n    gzip: true\n    level: 6\n    threshold: 1024\n\n  rate_limiting:\n    enabled: true\n    default_limit: 100\u002Fminute\n    burst_limit: 200\n    sliding_window: true\n\nsecurity:\n  authentication:\n    jwt_validation: true\n    token_refresh: true\n    revoke_tokens: true\n\n  authorization:\n    rbac: true\n    rate_limit_by_role: true\n\n  validation:\n    input_validation: true\n    sql_injection_protection: true\n    xss_protection: true\n\n  headers:\n    security_headers: true\n    cors: true\n    csrf_protection: true\n\nmonitoring:\n  metrics:\n    prometheus: true\n    request_duration: true\n    error_rate: true\n    throughput: true\n\n  logging:\n    structured_logging: true\n    correlation_ids: true\n    error_tracking: true\n\n  health_checks:\n    liveness_probe: true\n    readiness_probe: true\n    dependency_checks: true\n\ndocumentation:\n  openapi:\n    auto_generation: true\n    examples: true\n    schemas: true\n\n  versioning:\n    strategy: \"header_path_query\"\n    deprecation_warnings: true\n    backward_compatibility: true\n\n  testing:\n    unit_tests: true\n    integration_tests: true\n    performance_tests: true\n    contract_tests: true\n```\n\nThis comprehensive API development skill provides modern patterns for building high-performance APIs in 2025, including async\u002Fawait patterns, circuit breakers, rate limiting, versioning strategies, comprehensive testing, and production optimization techniques that work across different frameworks.",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fmarketplace\u002Fapi-dev",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill api-dev",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill api-dev",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill api-dev","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fapi-dev\u002FSKILL.md",true,[48],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"skill-report.json","REFERENCE","参考文档",41106,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fapi-dev\u002Fskill-report.json",[55,63,70,77,84,91],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":62},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":62},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":62},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":62},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":62},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":62},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]