[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6JDQMPXME98FAZY6QYA9VGT":3,"skill-same:01M6JDQMPXME98FAZY6QYA9VGT":83},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":30,"publishedAt":51,"linkOnly":52,"markdownContent":53,"markdownBody":54,"frontMatter":55,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":13,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":6,"ownerDescription":61,"updatedAt":62,"install":63,"resources":76},"01M6JDQMPXME98FAZY6QYA9VGT","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.","superhealth\u002Fskills-hub","superhealth","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6292112?v=4","01M6JA6E7F21BYK5W3E4P270TT","01M6JA6EC0W8MPHKDJVBZDSEZ0",0,"MIT","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fazeem-2\u002Fapi-dev\u002FSKILL.md",[17,22,25],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50],"dev","api","api dev","async","await","for","Scalable","middleware","error","high-performance","patterns","expert","testing","node","work","framework","development","documentation","performance","go","2026-11-10 10:12:30",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":14,"description":7},"master","08cc2532077058aa50e6e18f54695bc256c88152","skills\u002Fazeem-2\u002Fapi-dev","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub","https:\u002F\u002Fgithub.com\u002Fsuperhealth","java engineer","2026-04-06 22:07:23",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add superhealth\u002Fskills-hub --skill api-dev",{"tool":69,"command":70},"bunx","bunx skills add superhealth\u002Fskills-hub --skill api-dev",{"tool":72,"command":73},"pnpm","pnpm dlx skills add superhealth\u002Fskills-hub --skill api-dev","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fazeem-2\u002Fapi-dev\u002FSKILL.md",true,[77],{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"skill-report.json","REFERENCE","参考文档",14353,"https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fazeem-2\u002Fapi-dev\u002Fskill-report.json",[84,112,136,149,165,182],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":93,"publishedAt":51},"01M6MC9F3WHV8S8FZ2W4TRB0FE","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fzhanlincui\u002Fvercel-react-best-practices\u002FSKILL.md",[90],{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000009","前端开发",[94,95,96,97,98,99,100,101,102,103,41,104,105,106,107,108,109,110,49,111],"react","vercel react best practices","best practices","vercel","react best practices","data fetching","code","triggers","pages","next","refactoring","data","Optimization","tasks","guidelines","react components","components","writing",{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":120,"publishedAt":51},"01M6MB8KWE1Q5A5KERR7RFTQWP","vue-testing-best-practices","Use for Vue.js testing. Covers Vitest, Vue Test Utils, component testing, mocking, testing patterns, and Playwright for E2E testing.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fvuejs-ai\u002Fvue-testing-best-practices\u002FSKILL.md",[118,119],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},[121,122,123,96,43,124,125,126,127,128,129,41,130,131,36,132,133,134,135],"vue testing best practices","testing best practices","vue","testing patterns","js","e2e","vitest","use","component","test","mocking","utils","e2e testing","github","playwright",{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":143,"publishedAt":51},"01M6MB8GK06M6GA4KVYNDV1BZP","vue-router-best-practices","Vue Router 4 patterns, navigation guards, route params, and route-component lifecycle interactions.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fvuejs-ai\u002Fvue-router-best-practices\u002FSKILL.md",[142],{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},[96,123,144,145,146,41,147,148,129,134],"router","vue router best practices","route","navigation","lifecycle",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":156,"publishedAt":51},"01M6MB8DQF21TZMQ9XC3745ERW","vue-pinia-best-practices","Pinia stores, state management patterns, store setup, and reactivity with stores.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fvuejs-ai\u002Fvue-pinia-best-practices\u002FSKILL.md",[155],{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},[157,158,123,96,159,160,41,161,162,163,164,134],"vue pinia best practices","pinia","with","store","management","state","state management","setup",{"skillNo":166,"name":167,"nameZh":6,"description":168,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":169,"categories":170,"keywords":174,"publishedAt":51},"01M6MB8A7MC08747J9TV4GWQ9A","vue-options-api-best-practices","Vue 3 Options API style (data(), methods, this context). Each reference shows Options API solution only.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fvuejs-ai\u002Fvue-options-api-best-practices\u002FSKILL.md",[171,172,173],{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},[123,175,176,32,96,177,178,179,180,105,134,181],"options","vue options api best practices","methods","reference","only","context","style",{"skillNo":183,"name":184,"nameZh":6,"description":185,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":186,"categories":187,"keywords":189,"publishedAt":51},"01M6MB85ZTQC24Q04X49MM4YXN","vue-development-guides","A collection of best practices and tips for developing applications using Vue.js. This skill MUST be apply when developing, refactoring or reviewing Vue.js or Nuxt projects.","https:\u002F\u002Fgithub.com\u002Fsuperhealth\u002Fskills-hub\u002Fblob\u002Fmaster\u002Fskills\u002Fvuejs-ai\u002Fvue-development-guides\u002FSKILL.md",[188],{"categoryNo":91,"categoryName":92,"taxonomyType":20,"taxonomyTypeDesc":21},[47,123,190,191,134,192,193,36,194,195,196,125,104,197,198,96],"guides","vue development guides","tips","apply","project","nuxt","projects","collection","applications"]