[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AFZZJA6EE9BBTSPHMXGPKP":3,"skill-same:01M6AFZZJA6EE9BBTSPHMXGPKP":86},{"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":28,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":62,"commitSha":63,"skillDirectory":64,"forksCount":65,"repositoryHtmlUrl":66,"repositoryHomepageUrl":67,"ownerHtmlUrl":68,"ownerBlogUrl":69,"ownerDescription":70,"updatedAt":71,"install":72,"resources":85},"01M6AFZZJA6EE9BBTSPHMXGPKP","fastapi-endpoint",null,"Plan and build production-ready FastAPI endpoints with async SQLAlchemy, Pydantic v2 models, dependency injection for auth, and pytest tests. Uses interview-driven planning to clarify data models, authentication method, pagination strategy, and caching before writing any code.","davila7\u002Fclaude-code-templates","davila7","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6216945?v=4","01M6ADEWWFPS191NFM0Y1EX1JH","Daniel Avila","01M6ADJHGM78PHQRD3XZTFDVKK",33332,"MIT","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"fastapi","endpoint","fastapi endpoint","api","production-ready","sqlalchemy","caching","pytest","ready","dependency","interview","clarify","plan","writing","injection","Production","Pydantic","data","authentication","planning","code","auth","python","2026-11-10 10:12:30",false,"---\nname: fastapi-endpoint\ndescription: Plan and build production-ready FastAPI endpoints with async SQLAlchemy, Pydantic v2 models, dependency injection for auth, and pytest tests. Uses interview-driven planning to clarify data models, authentication method, pagination strategy, and caching before writing any code.\nmetadata:\n  tags: [fastapi, python, api, async, pydantic, sqlalchemy, backend]\n---\n\n# FastAPI Endpoint Builder\n\n## When to use\n\nUse this skill when you need to:\n\n- Add new API endpoints to an existing FastAPI project\n- Build CRUD operations with proper validation and error handling\n- Set up authenticated endpoints with dependency injection\n- Create async database queries with SQLAlchemy 2.0\n- Generate complete test coverage for API routes\n\n## Phase 1: Explore (Plan Mode)\n\nEnter plan mode. Before writing any code, explore the existing project to understand:\n\n### Project structure\n- Find the FastAPI app entry point (`main.py`, `app.py`, or `app\u002F__init__.py`)\n- Identify the router organization pattern (single file vs `routers\u002F` directory)\n- Check for existing `models\u002F`, `schemas\u002F`, `crud\u002F`, or `services\u002F` directories\n- Look at `pyproject.toml` or `requirements.txt` for installed dependencies\n\n### Existing patterns\n- How are existing endpoints structured? (function-based vs class-based)\n- What ORM is used? (SQLAlchemy 2.0 async, Tortoise, raw SQL, none)\n- How is the database session managed? (`Depends(get_db)`, middleware, other)\n- What auth pattern exists? (OAuth2PasswordBearer, API key header, custom)\n- Are there existing Pydantic base models or shared schemas?\n- What response format is standard? (direct model, wrapped `{\"data\": ..., \"meta\": ...}`)\n\n### Test patterns\n- Where do tests live? (`tests\u002F`, `test_*.py`, `*_test.py`)\n- What test client is used? (httpx AsyncClient, TestClient, pytest-asyncio)\n- Are there test fixtures for database and auth?\n\n## Phase 2: Interview (AskUserQuestion)\n\nUse AskUserQuestion to clarify requirements. Ask in rounds — do NOT dump all questions at once.\n\n### Round 1: Core endpoint\n\n```\nQuestion: \"What resource does this endpoint manage?\"\nHeader: \"Resource\"\nOptions:\n  - \"New resource (I'll describe the fields)\" — Creating a new data model from scratch\n  - \"Existing model (extend it)\" — Adding endpoints for a model that already exists in the codebase\n  - \"Relationship endpoint (nested)\" — e.g., \u002Fusers\u002F{id}\u002Forders — endpoint on a related resource\n\nQuestion: \"Which HTTP methods do you need?\"\nHeader: \"Methods\"\nmultiSelect: true\nOptions:\n  - \"Full CRUD (GET list, GET detail, POST, PUT\u002FPATCH, DELETE)\" — All standard operations\n  - \"Read-only (GET list + GET detail)\" — No mutations\n  - \"Custom action (POST \u002Fresource\u002F{id}\u002Faction)\" — Business logic endpoint, not standard CRUD\n```\n\n### Round 2: Data model (if new resource)\n\n```\nQuestion: \"What fields does the resource have? (describe briefly)\"\nHeader: \"Fields\"\nOptions:\n  - \"Simple (\u003C 6 fields, basic types)\" — Strings, ints, booleans, dates\n  - \"Medium (6-15 fields, some relations)\" — Includes foreign keys or enums\n  - \"Complex (nested objects, polymorphic)\" — JSON fields, discriminated unions, computed fields\n```\n\n### Round 3: Auth and access control\n\n```\nQuestion: \"How should this endpoint be authenticated?\"\nHeader: \"Auth\"\nOptions:\n  - \"JWT Bearer token (Recommended)\" — OAuth2PasswordBearer with JWT decode\n  - \"API Key header\" — X-API-Key header validation\n  - \"No auth (public)\" — Open endpoint, no authentication required\n  - \"Use existing auth\" — Reuse the auth dependency already in the project\n\nQuestion: \"Do you need role-based access control?\"\nHeader: \"RBAC\"\nOptions:\n  - \"No — any authenticated user\" — Single permission level\n  - \"Yes — role check (admin, user, etc.)\" — Require specific roles per endpoint\n  - \"Yes — ownership check\" — Users can only access their own resources\n```\n\n### Round 4: Pagination, filtering, caching\n\n```\nQuestion: \"What pagination style for list endpoints?\"\nHeader: \"Pagination\"\nOptions:\n  - \"Cursor-based (Recommended)\" — Best for real-time data, no offset drift\n  - \"Offset\u002Flimit\" — Simple, good for admin panels with page numbers\n  - \"No pagination\" — Small datasets, return all results\n\nQuestion: \"Do you need response caching?\"\nHeader: \"Caching\"\nOptions:\n  - \"No caching\" — Fresh data on every request\n  - \"Cache-Control headers\" — Client-side caching via HTTP headers\n  - \"Redis\u002Fin-memory cache\" — Server-side caching with TTL\n```\n\n## Phase 3: Plan (ExitPlanMode)\n\nWrite a concrete implementation plan covering:\n\n1. **Files to create\u002Fmodify** — exact paths based on project structure discovered in Phase 1\n2. **Pydantic schemas** — `Create`, `Update`, `Response`, and `List` schemas with field types\n3. **SQLAlchemy model** — table name, columns, relationships, indexes\n4. **CRUD\u002Fservice layer** — async functions for each operation\n5. **Router** — endpoint signatures, status codes, response models\n6. **Dependencies** — auth, pagination, filtering dependencies\n7. **Tests** — test cases for happy path, validation errors, auth failures, not found\n\nPresent via ExitPlanMode for user approval.\n\n## Phase 4: Execute\n\nAfter approval, implement following this order:\n\n### Step 1: Pydantic schemas\n\n```python\nfrom pydantic import BaseModel, ConfigDict\nfrom datetime import datetime\nfrom uuid import UUID\n\nclass ResourceBase(BaseModel):\n    \"\"\"Shared fields between create and response.\"\"\"\n    name: str\n    # ... fields from interview\n\nclass ResourceCreate(ResourceBase):\n    \"\"\"Fields required to create the resource.\"\"\"\n    pass\n\nclass ResourceUpdate(BaseModel):\n    \"\"\"All fields optional for partial updates.\"\"\"\n    name: str | None = None\n\nclass ResourceResponse(ResourceBase):\n    \"\"\"Full resource with DB-generated fields.\"\"\"\n    model_config = ConfigDict(from_attributes=True)\n    id: UUID\n    created_at: datetime\n    updated_at: datetime\n\nclass ResourceListResponse(BaseModel):\n    \"\"\"Paginated list response.\"\"\"\n    data: list[ResourceResponse]\n    next_cursor: str | None = None\n    has_more: bool\n```\n\n### Step 2: SQLAlchemy model\n\n```python\nfrom sqlalchemy import Column, String, DateTime, func\nfrom sqlalchemy.dialects.postgresql import UUID as PG_UUID\nimport uuid\nfrom app.database import Base\n\nclass Resource(Base):\n    __tablename__ = \"resources\"\n\n    id = Column(PG_UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\n    name = Column(String, nullable=False, index=True)\n    created_at = Column(DateTime(timezone=True), server_default=func.now())\n    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())\n```\n\n### Step 3: CRUD\u002Fservice layer\n\n```python\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy import select\nfrom uuid import UUID\n\nasync def get_resource(db: AsyncSession, resource_id: UUID) -> Resource | None:\n    result = await db.execute(select(Resource).where(Resource.id == resource_id))\n    return result.scalar_one_or_none()\n\nasync def list_resources(\n    db: AsyncSession,\n    cursor: str | None = None,\n    limit: int = 20,\n) -> tuple[list[Resource], str | None]:\n    query = select(Resource).order_by(Resource.created_at.desc()).limit(limit + 1)\n    if cursor:\n        query = query.where(Resource.created_at \u003C decode_cursor(cursor))\n    result = await db.execute(query)\n    items = list(result.scalars().all())\n    next_cursor = encode_cursor(items[-1].created_at) if len(items) > limit else None\n    return items[:limit], next_cursor\n\nasync def create_resource(db: AsyncSession, data: ResourceCreate) -> Resource:\n    resource = Resource(**data.model_dump())\n    db.add(resource)\n    await db.commit()\n    await db.refresh(resource)\n    return resource\n\nasync def update_resource(\n    db: AsyncSession, resource_id: UUID, data: ResourceUpdate\n) -> Resource | None:\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        return None\n    for field, value in data.model_dump(exclude_unset=True).items():\n        setattr(resource, field, value)\n    await db.commit()\n    await db.refresh(resource)\n    return resource\n\nasync def delete_resource(db: AsyncSession, resource_id: UUID) -> bool:\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        return False\n    await db.delete(resource)\n    await db.commit()\n    return True\n```\n\n### Step 4: Router with dependencies\n\n```python\nfrom fastapi import APIRouter, Depends, HTTPException, Query, status\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom uuid import UUID\n\nrouter = APIRouter(prefix=\"\u002Fresources\", tags=[\"resources\"])\n\n@router.get(\"\", response_model=ResourceListResponse)\nasync def list_resources_endpoint(\n    cursor: str | None = Query(None),\n    limit: int = Query(20, ge=1, le=100),\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),  # if auth required\n):\n    items, next_cursor = await list_resources(db, cursor=cursor, limit=limit)\n    return ResourceListResponse(\n        data=items,\n        next_cursor=next_cursor,\n        has_more=next_cursor is not None,\n    )\n\n@router.get(\"\u002F{resource_id}\", response_model=ResourceResponse)\nasync def get_resource_endpoint(\n    resource_id: UUID,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n    return resource\n\n@router.post(\"\", response_model=ResourceResponse, status_code=status.HTTP_201_CREATED)\nasync def create_resource_endpoint(\n    data: ResourceCreate,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    return await create_resource(db, data)\n\n@router.patch(\"\u002F{resource_id}\", response_model=ResourceResponse)\nasync def update_resource_endpoint(\n    resource_id: UUID,\n    data: ResourceUpdate,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    resource = await update_resource(db, resource_id, data)\n    if not resource:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n    return resource\n\n@router.delete(\"\u002F{resource_id}\", status_code=status.HTTP_204_NO_CONTENT)\nasync def delete_resource_endpoint(\n    resource_id: UUID,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    deleted = await delete_resource(db, resource_id)\n    if not deleted:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n```\n\n### Step 5: Tests\n\n```python\nimport pytest\nfrom httpx import AsyncClient, ASGITransport\nfrom app.main import app\n\n@pytest.fixture\nasync def client():\n    async with AsyncClient(\n        transport=ASGITransport(app=app), base_url=\"http:\u002F\u002Ftest\"\n    ) as ac:\n        yield ac\n\n@pytest.mark.asyncio\nasync def test_create_resource(client: AsyncClient, auth_headers: dict):\n    response = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"Test Resource\"},\n        headers=auth_headers,\n    )\n    assert response.status_code == 201\n    data = response.json()\n    assert data[\"name\"] == \"Test Resource\"\n    assert \"id\" in data\n\n@pytest.mark.asyncio\nasync def test_get_resource_not_found(client: AsyncClient, auth_headers: dict):\n    response = await client.get(\n        \"\u002Fresources\u002F00000000-0000-0000-0000-000000000000\",\n        headers=auth_headers,\n    )\n    assert response.status_code == 404\n\n@pytest.mark.asyncio\nasync def test_list_resources_pagination(client: AsyncClient, auth_headers: dict):\n    # Create multiple resources first\n    for i in range(5):\n        await client.post(\n            \"\u002Fresources\",\n            json={\"name\": f\"Resource {i}\"},\n            headers=auth_headers,\n        )\n    response = await client.get(\"\u002Fresources?limit=2\", headers=auth_headers)\n    assert response.status_code == 200\n    data = response.json()\n    assert len(data[\"data\"]) == 2\n    assert data[\"has_more\"] is True\n    assert data[\"next_cursor\"] is not None\n\n@pytest.mark.asyncio\nasync def test_create_resource_unauthorized(client: AsyncClient):\n    response = await client.post(\"\u002Fresources\", json={\"name\": \"Test\"})\n    assert response.status_code in (401, 403)\n\n@pytest.mark.asyncio\nasync def test_update_resource_partial(client: AsyncClient, auth_headers: dict):\n    # Create\n    create_resp = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"Original\"},\n        headers=auth_headers,\n    )\n    resource_id = create_resp.json()[\"id\"]\n    # Partial update\n    response = await client.patch(\n        f\"\u002Fresources\u002F{resource_id}\",\n        json={\"name\": \"Updated\"},\n        headers=auth_headers,\n    )\n    assert response.status_code == 200\n    assert response.json()[\"name\"] == \"Updated\"\n\n@pytest.mark.asyncio\nasync def test_delete_resource(client: AsyncClient, auth_headers: dict):\n    create_resp = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"To Delete\"},\n        headers=auth_headers,\n    )\n    resource_id = create_resp.json()[\"id\"]\n    response = await client.delete(\n        f\"\u002Fresources\u002F{resource_id}\", headers=auth_headers\n    )\n    assert response.status_code == 204\n    # Verify deleted\n    get_resp = await client.get(\n        f\"\u002Fresources\u002F{resource_id}\", headers=auth_headers\n    )\n    assert get_resp.status_code == 404\n```\n\n## Key patterns to follow\n\n### Dependency injection for auth\n\n```python\nfrom fastapi import Depends, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"auth\u002Ftoken\")\n\nasync def get_current_user(\n    token: str = Depends(oauth2_scheme),\n    db: AsyncSession = Depends(get_db),\n) -> User:\n    payload = decode_jwt(token)\n    user = await db.get(User, payload[\"sub\"])\n    if not user:\n        raise HTTPException(status_code=401, detail=\"Invalid token\")\n    return user\n\ndef require_role(*roles: str):\n    \"\"\"Factory for role-based access control.\"\"\"\n    async def checker(current_user: User = Depends(get_current_user)):\n        if current_user.role not in roles:\n            raise HTTPException(status_code=403, detail=\"Insufficient permissions\")\n        return current_user\n    return checker\n```\n\n### Cursor-based pagination helper\n\n```python\nimport base64\nfrom datetime import datetime\n\ndef encode_cursor(dt: datetime) -> str:\n    return base64.urlsafe_b64encode(dt.isoformat().encode()).decode()\n\ndef decode_cursor(cursor: str) -> datetime:\n    return datetime.fromisoformat(base64.urlsafe_b64decode(cursor).decode())\n```\n\n### Error responses\n\nAlways use FastAPI's `HTTPException` with consistent detail messages. For validation errors, Pydantic v2 handles them automatically via `RequestValidationError` (422).\n\n```python\n# 404 — not found\nraise HTTPException(status_code=404, detail=\"Resource not found\")\n\n# 409 — conflict (duplicate)\nraise HTTPException(status_code=409, detail=\"Resource with this name already exists\")\n\n# 403 — forbidden\nraise HTTPException(status_code=403, detail=\"Not allowed to modify this resource\")\n```\n\n## Checklist before finishing\n\n- [ ] All endpoints return proper status codes (201 for POST, 204 for DELETE)\n- [ ] Pydantic schemas use `model_config = ConfigDict(from_attributes=True)` for ORM mode\n- [ ] List endpoint has pagination with configurable limit\n- [ ] Auth dependency is applied to all non-public endpoints\n- [ ] Tests cover: happy path, not found, unauthorized, validation errors\n- [ ] Router is registered in the main FastAPI app\n- [ ] Database model has proper indexes on filtered\u002Fsorted columns\n","# FastAPI Endpoint Builder\n\n## When to use\n\nUse this skill when you need to:\n\n- Add new API endpoints to an existing FastAPI project\n- Build CRUD operations with proper validation and error handling\n- Set up authenticated endpoints with dependency injection\n- Create async database queries with SQLAlchemy 2.0\n- Generate complete test coverage for API routes\n\n## Phase 1: Explore (Plan Mode)\n\nEnter plan mode. Before writing any code, explore the existing project to understand:\n\n### Project structure\n- Find the FastAPI app entry point (`main.py`, `app.py`, or `app\u002F__init__.py`)\n- Identify the router organization pattern (single file vs `routers\u002F` directory)\n- Check for existing `models\u002F`, `schemas\u002F`, `crud\u002F`, or `services\u002F` directories\n- Look at `pyproject.toml` or `requirements.txt` for installed dependencies\n\n### Existing patterns\n- How are existing endpoints structured? (function-based vs class-based)\n- What ORM is used? (SQLAlchemy 2.0 async, Tortoise, raw SQL, none)\n- How is the database session managed? (`Depends(get_db)`, middleware, other)\n- What auth pattern exists? (OAuth2PasswordBearer, API key header, custom)\n- Are there existing Pydantic base models or shared schemas?\n- What response format is standard? (direct model, wrapped `{\"data\": ..., \"meta\": ...}`)\n\n### Test patterns\n- Where do tests live? (`tests\u002F`, `test_*.py`, `*_test.py`)\n- What test client is used? (httpx AsyncClient, TestClient, pytest-asyncio)\n- Are there test fixtures for database and auth?\n\n## Phase 2: Interview (AskUserQuestion)\n\nUse AskUserQuestion to clarify requirements. Ask in rounds — do NOT dump all questions at once.\n\n### Round 1: Core endpoint\n\n```\nQuestion: \"What resource does this endpoint manage?\"\nHeader: \"Resource\"\nOptions:\n  - \"New resource (I'll describe the fields)\" — Creating a new data model from scratch\n  - \"Existing model (extend it)\" — Adding endpoints for a model that already exists in the codebase\n  - \"Relationship endpoint (nested)\" — e.g., \u002Fusers\u002F{id}\u002Forders — endpoint on a related resource\n\nQuestion: \"Which HTTP methods do you need?\"\nHeader: \"Methods\"\nmultiSelect: true\nOptions:\n  - \"Full CRUD (GET list, GET detail, POST, PUT\u002FPATCH, DELETE)\" — All standard operations\n  - \"Read-only (GET list + GET detail)\" — No mutations\n  - \"Custom action (POST \u002Fresource\u002F{id}\u002Faction)\" — Business logic endpoint, not standard CRUD\n```\n\n### Round 2: Data model (if new resource)\n\n```\nQuestion: \"What fields does the resource have? (describe briefly)\"\nHeader: \"Fields\"\nOptions:\n  - \"Simple (\u003C 6 fields, basic types)\" — Strings, ints, booleans, dates\n  - \"Medium (6-15 fields, some relations)\" — Includes foreign keys or enums\n  - \"Complex (nested objects, polymorphic)\" — JSON fields, discriminated unions, computed fields\n```\n\n### Round 3: Auth and access control\n\n```\nQuestion: \"How should this endpoint be authenticated?\"\nHeader: \"Auth\"\nOptions:\n  - \"JWT Bearer token (Recommended)\" — OAuth2PasswordBearer with JWT decode\n  - \"API Key header\" — X-API-Key header validation\n  - \"No auth (public)\" — Open endpoint, no authentication required\n  - \"Use existing auth\" — Reuse the auth dependency already in the project\n\nQuestion: \"Do you need role-based access control?\"\nHeader: \"RBAC\"\nOptions:\n  - \"No — any authenticated user\" — Single permission level\n  - \"Yes — role check (admin, user, etc.)\" — Require specific roles per endpoint\n  - \"Yes — ownership check\" — Users can only access their own resources\n```\n\n### Round 4: Pagination, filtering, caching\n\n```\nQuestion: \"What pagination style for list endpoints?\"\nHeader: \"Pagination\"\nOptions:\n  - \"Cursor-based (Recommended)\" — Best for real-time data, no offset drift\n  - \"Offset\u002Flimit\" — Simple, good for admin panels with page numbers\n  - \"No pagination\" — Small datasets, return all results\n\nQuestion: \"Do you need response caching?\"\nHeader: \"Caching\"\nOptions:\n  - \"No caching\" — Fresh data on every request\n  - \"Cache-Control headers\" — Client-side caching via HTTP headers\n  - \"Redis\u002Fin-memory cache\" — Server-side caching with TTL\n```\n\n## Phase 3: Plan (ExitPlanMode)\n\nWrite a concrete implementation plan covering:\n\n1. **Files to create\u002Fmodify** — exact paths based on project structure discovered in Phase 1\n2. **Pydantic schemas** — `Create`, `Update`, `Response`, and `List` schemas with field types\n3. **SQLAlchemy model** — table name, columns, relationships, indexes\n4. **CRUD\u002Fservice layer** — async functions for each operation\n5. **Router** — endpoint signatures, status codes, response models\n6. **Dependencies** — auth, pagination, filtering dependencies\n7. **Tests** — test cases for happy path, validation errors, auth failures, not found\n\nPresent via ExitPlanMode for user approval.\n\n## Phase 4: Execute\n\nAfter approval, implement following this order:\n\n### Step 1: Pydantic schemas\n\n```python\nfrom pydantic import BaseModel, ConfigDict\nfrom datetime import datetime\nfrom uuid import UUID\n\nclass ResourceBase(BaseModel):\n    \"\"\"Shared fields between create and response.\"\"\"\n    name: str\n    # ... fields from interview\n\nclass ResourceCreate(ResourceBase):\n    \"\"\"Fields required to create the resource.\"\"\"\n    pass\n\nclass ResourceUpdate(BaseModel):\n    \"\"\"All fields optional for partial updates.\"\"\"\n    name: str | None = None\n\nclass ResourceResponse(ResourceBase):\n    \"\"\"Full resource with DB-generated fields.\"\"\"\n    model_config = ConfigDict(from_attributes=True)\n    id: UUID\n    created_at: datetime\n    updated_at: datetime\n\nclass ResourceListResponse(BaseModel):\n    \"\"\"Paginated list response.\"\"\"\n    data: list[ResourceResponse]\n    next_cursor: str | None = None\n    has_more: bool\n```\n\n### Step 2: SQLAlchemy model\n\n```python\nfrom sqlalchemy import Column, String, DateTime, func\nfrom sqlalchemy.dialects.postgresql import UUID as PG_UUID\nimport uuid\nfrom app.database import Base\n\nclass Resource(Base):\n    __tablename__ = \"resources\"\n\n    id = Column(PG_UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)\n    name = Column(String, nullable=False, index=True)\n    created_at = Column(DateTime(timezone=True), server_default=func.now())\n    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())\n```\n\n### Step 3: CRUD\u002Fservice layer\n\n```python\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom sqlalchemy import select\nfrom uuid import UUID\n\nasync def get_resource(db: AsyncSession, resource_id: UUID) -> Resource | None:\n    result = await db.execute(select(Resource).where(Resource.id == resource_id))\n    return result.scalar_one_or_none()\n\nasync def list_resources(\n    db: AsyncSession,\n    cursor: str | None = None,\n    limit: int = 20,\n) -> tuple[list[Resource], str | None]:\n    query = select(Resource).order_by(Resource.created_at.desc()).limit(limit + 1)\n    if cursor:\n        query = query.where(Resource.created_at \u003C decode_cursor(cursor))\n    result = await db.execute(query)\n    items = list(result.scalars().all())\n    next_cursor = encode_cursor(items[-1].created_at) if len(items) > limit else None\n    return items[:limit], next_cursor\n\nasync def create_resource(db: AsyncSession, data: ResourceCreate) -> Resource:\n    resource = Resource(**data.model_dump())\n    db.add(resource)\n    await db.commit()\n    await db.refresh(resource)\n    return resource\n\nasync def update_resource(\n    db: AsyncSession, resource_id: UUID, data: ResourceUpdate\n) -> Resource | None:\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        return None\n    for field, value in data.model_dump(exclude_unset=True).items():\n        setattr(resource, field, value)\n    await db.commit()\n    await db.refresh(resource)\n    return resource\n\nasync def delete_resource(db: AsyncSession, resource_id: UUID) -> bool:\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        return False\n    await db.delete(resource)\n    await db.commit()\n    return True\n```\n\n### Step 4: Router with dependencies\n\n```python\nfrom fastapi import APIRouter, Depends, HTTPException, Query, status\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom uuid import UUID\n\nrouter = APIRouter(prefix=\"\u002Fresources\", tags=[\"resources\"])\n\n@router.get(\"\", response_model=ResourceListResponse)\nasync def list_resources_endpoint(\n    cursor: str | None = Query(None),\n    limit: int = Query(20, ge=1, le=100),\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),  # if auth required\n):\n    items, next_cursor = await list_resources(db, cursor=cursor, limit=limit)\n    return ResourceListResponse(\n        data=items,\n        next_cursor=next_cursor,\n        has_more=next_cursor is not None,\n    )\n\n@router.get(\"\u002F{resource_id}\", response_model=ResourceResponse)\nasync def get_resource_endpoint(\n    resource_id: UUID,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    resource = await get_resource(db, resource_id)\n    if not resource:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n    return resource\n\n@router.post(\"\", response_model=ResourceResponse, status_code=status.HTTP_201_CREATED)\nasync def create_resource_endpoint(\n    data: ResourceCreate,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    return await create_resource(db, data)\n\n@router.patch(\"\u002F{resource_id}\", response_model=ResourceResponse)\nasync def update_resource_endpoint(\n    resource_id: UUID,\n    data: ResourceUpdate,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    resource = await update_resource(db, resource_id, data)\n    if not resource:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n    return resource\n\n@router.delete(\"\u002F{resource_id}\", status_code=status.HTTP_204_NO_CONTENT)\nasync def delete_resource_endpoint(\n    resource_id: UUID,\n    db: AsyncSession = Depends(get_db),\n    current_user: User = Depends(get_current_user),\n):\n    deleted = await delete_resource(db, resource_id)\n    if not deleted:\n        raise HTTPException(status_code=404, detail=\"Resource not found\")\n```\n\n### Step 5: Tests\n\n```python\nimport pytest\nfrom httpx import AsyncClient, ASGITransport\nfrom app.main import app\n\n@pytest.fixture\nasync def client():\n    async with AsyncClient(\n        transport=ASGITransport(app=app), base_url=\"http:\u002F\u002Ftest\"\n    ) as ac:\n        yield ac\n\n@pytest.mark.asyncio\nasync def test_create_resource(client: AsyncClient, auth_headers: dict):\n    response = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"Test Resource\"},\n        headers=auth_headers,\n    )\n    assert response.status_code == 201\n    data = response.json()\n    assert data[\"name\"] == \"Test Resource\"\n    assert \"id\" in data\n\n@pytest.mark.asyncio\nasync def test_get_resource_not_found(client: AsyncClient, auth_headers: dict):\n    response = await client.get(\n        \"\u002Fresources\u002F00000000-0000-0000-0000-000000000000\",\n        headers=auth_headers,\n    )\n    assert response.status_code == 404\n\n@pytest.mark.asyncio\nasync def test_list_resources_pagination(client: AsyncClient, auth_headers: dict):\n    # Create multiple resources first\n    for i in range(5):\n        await client.post(\n            \"\u002Fresources\",\n            json={\"name\": f\"Resource {i}\"},\n            headers=auth_headers,\n        )\n    response = await client.get(\"\u002Fresources?limit=2\", headers=auth_headers)\n    assert response.status_code == 200\n    data = response.json()\n    assert len(data[\"data\"]) == 2\n    assert data[\"has_more\"] is True\n    assert data[\"next_cursor\"] is not None\n\n@pytest.mark.asyncio\nasync def test_create_resource_unauthorized(client: AsyncClient):\n    response = await client.post(\"\u002Fresources\", json={\"name\": \"Test\"})\n    assert response.status_code in (401, 403)\n\n@pytest.mark.asyncio\nasync def test_update_resource_partial(client: AsyncClient, auth_headers: dict):\n    # Create\n    create_resp = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"Original\"},\n        headers=auth_headers,\n    )\n    resource_id = create_resp.json()[\"id\"]\n    # Partial update\n    response = await client.patch(\n        f\"\u002Fresources\u002F{resource_id}\",\n        json={\"name\": \"Updated\"},\n        headers=auth_headers,\n    )\n    assert response.status_code == 200\n    assert response.json()[\"name\"] == \"Updated\"\n\n@pytest.mark.asyncio\nasync def test_delete_resource(client: AsyncClient, auth_headers: dict):\n    create_resp = await client.post(\n        \"\u002Fresources\",\n        json={\"name\": \"To Delete\"},\n        headers=auth_headers,\n    )\n    resource_id = create_resp.json()[\"id\"]\n    response = await client.delete(\n        f\"\u002Fresources\u002F{resource_id}\", headers=auth_headers\n    )\n    assert response.status_code == 204\n    # Verify deleted\n    get_resp = await client.get(\n        f\"\u002Fresources\u002F{resource_id}\", headers=auth_headers\n    )\n    assert get_resp.status_code == 404\n```\n\n## Key patterns to follow\n\n### Dependency injection for auth\n\n```python\nfrom fastapi import Depends, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer\n\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"auth\u002Ftoken\")\n\nasync def get_current_user(\n    token: str = Depends(oauth2_scheme),\n    db: AsyncSession = Depends(get_db),\n) -> User:\n    payload = decode_jwt(token)\n    user = await db.get(User, payload[\"sub\"])\n    if not user:\n        raise HTTPException(status_code=401, detail=\"Invalid token\")\n    return user\n\ndef require_role(*roles: str):\n    \"\"\"Factory for role-based access control.\"\"\"\n    async def checker(current_user: User = Depends(get_current_user)):\n        if current_user.role not in roles:\n            raise HTTPException(status_code=403, detail=\"Insufficient permissions\")\n        return current_user\n    return checker\n```\n\n### Cursor-based pagination helper\n\n```python\nimport base64\nfrom datetime import datetime\n\ndef encode_cursor(dt: datetime) -> str:\n    return base64.urlsafe_b64encode(dt.isoformat().encode()).decode()\n\ndef decode_cursor(cursor: str) -> datetime:\n    return datetime.fromisoformat(base64.urlsafe_b64decode(cursor).decode())\n```\n\n### Error responses\n\nAlways use FastAPI's `HTTPException` with consistent detail messages. For validation errors, Pydantic v2 handles them automatically via `RequestValidationError` (422).\n\n```python\n# 404 — not found\nraise HTTPException(status_code=404, detail=\"Resource not found\")\n\n# 409 — conflict (duplicate)\nraise HTTPException(status_code=409, detail=\"Resource with this name already exists\")\n\n# 403 — forbidden\nraise HTTPException(status_code=403, detail=\"Not allowed to modify this resource\")\n```\n\n## Checklist before finishing\n\n- [ ] All endpoints return proper status codes (201 for POST, 204 for DELETE)\n- [ ] Pydantic schemas use `model_config = ConfigDict(from_attributes=True)` for ORM mode\n- [ ] List endpoint has pagination with configurable limit\n- [ ] Auth dependency is applied to all non-public endpoints\n- [ ] Tests cover: happy path, not found, unauthorized, validation errors\n- [ ] Router is registered in the main FastAPI app\n- [ ] Database model has proper indexes on filtered\u002Fsorted columns\n",{"name":5,"metadata":57,"description":7},{"tags":58},[29,51,32,59,60,34,61],"async","pydantic","backend","main","2b749c82b5d11fac39d9a6e021ce3f5b8a541bd1","cli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint",3911,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates","https:\u002F\u002Faitmpl.com","https:\u002F\u002Fgithub.com\u002Fdavila7","https:\u002F\u002Fdanielavila.me","Building AI dev tools with LLMs","2026-11-11 21:38:31",{"source":8,"skillName":5,"commands":73,"prompt":83,"zipAvailable":84},[74,77,80],{"tool":75,"command":76},"npx","npx skills add davila7\u002Fclaude-code-templates --skill fastapi-endpoint",{"tool":78,"command":79},"bunx","bunx skills add davila7\u002Fclaude-code-templates --skill fastapi-endpoint",{"tool":81,"command":82},"pnpm","pnpm dlx skills add davila7\u002Fclaude-code-templates --skill fastapi-endpoint","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint\u002FSKILL.md",true,[],[87,117,141,170,205,229],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":96,"publishedAt":52},"01M70NHBTQ8BV0A2SCAZXEPHCX","wealthville-pool-scoring","Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter\u002FHold\u002FExit\u002FReduce\u002FAvoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-data\u002Fwealthville-pool-scoring\u002FSKILL.md",[93],{"categoryNo":94,"categoryName":95,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116],"scoring","pool","wealthville pool scoring","liquidity","which","for","exit","now","use","when","reduce","with","record","track","verdict","evm","solana","how","public","look",{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":124,"publishedAt":52},"01M70MB6VR8ERJ4EM8D5KHBMEV","technical-debt-auditor","Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO\u002FFIXME\u002FHACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like \"where should I focus refactoring\", \"find code smells\", \"audit my codebase\", \"what technical debt do we have\", \"prioritize cleanup work\", or asks about code quality metrics. Also trigger when the user mentions \"code rot\", \"legacy cleanup\", \"refactoring priorities\", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say \"technical debt\" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Ftechnical-debt-auditor\u002FSKILL.md",[123],{"categoryNo":94,"categoryName":95,"taxonomyType":21,"taxonomyTypeDesc":22},[125,126,127,128,129,130,131,132,133,134,135,106,49,136,137,41,138,139,140,38],"technical debt","debt","technical","technical debt auditor","auditor","coverage","complexity","markers","project","cleanup","unused","todo","work","focus","signals","audit",{"skillNo":142,"name":143,"nameZh":6,"description":144,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":145,"categories":146,"keywords":152,"publishedAt":52},"01M70KPYH9QNHCNME5GJQGE22K","readonly-sql-guard","Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production\u002FERP\u002Fanalytics database (a \"query\" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write\u002FDDL\u002Fside-effect\u002Ftransaction-escape risks. Checks what a statement CALLS, not just its shape.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdatabase\u002Freadonly-sql-guard\u002FSKILL.md",[147,148,149],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":94,"categoryName":95,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":150,"categoryName":151,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000033","数据分析师",[153,154,155,156,157,158,159,102,160,161,162,163,164,165,166,105,167,168,106,169],"readonly","guard","sql guard","sql","readonly sql guard","erp","effect","read-only","db","just","tool","calls","only","MCP","access","database","query",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":174,"licenseFileUrl":175,"sourceHtmlUrl":176,"categories":177,"keywords":181,"publishedAt":52},"01M6AFY6F7CC2BBZP1QD6VTNVC","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[178],{"categoryNo":179,"categoryName":180,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,102,204],"artifacts builder","web","web artifacts builder","artifacts","builder","state","routing","state management","component","css","frontend","ui","Tools","file","components","shadcn","react","Tailwind","suite","jsx","html","single-file","ui components",{"skillNo":206,"name":207,"nameZh":6,"description":208,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":174,"licenseFileUrl":209,"sourceHtmlUrl":210,"categories":211,"keywords":216,"publishedAt":52},"01M6AFWF33SFV9Z3SF4PEEE4BF","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[212,215],{"categoryNo":213,"categoryName":214,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":179,"categoryName":180,"taxonomyType":21,"taxonomyTypeDesc":22},[217,218,219,220,221,183,222,192,193,223,224,225,226,102,227,108,228],"webapp testing","testing","webapp","browser","playwright","applications","debugging","toolkit","logs","screenshots","local","behavior",{"skillNo":230,"name":231,"nameZh":6,"description":232,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":174,"licenseFileUrl":233,"sourceHtmlUrl":234,"categories":235,"keywords":243,"publishedAt":52},"01M6AF67Q67JJJ5V51JR2P52KA","discernment-nudge","After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FSKILL.md",[236,239,240],{"categoryNo":237,"categoryName":238,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":94,"categoryName":95,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":241,"categoryName":242,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000036","内容创作者",[244,245,246,247,248,249,46,42,185,250,195,49,251,252,253,254,255,165,256,106,257,258,259,260,261,114,262],"discernment nudge","nudge","interpretation","help","run","reasoning","lookup","content","review","conversation","short","up","invoke","you","analysis","claims","argument","assemble","recommendations"]