[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CPJFD6VRSTKJB3FFA4KS4H":3,"skill-same:01M7CPJFD6VRSTKJB3FFA4KS4H":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":36,"repositoryHomepageUrl":6,"ownerHtmlUrl":37,"ownerBlogUrl":6,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M7CPJFD6VRSTKJB3FFA4KS4H","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.","Carchaloneo22\u002FClaude-Code-template","Carchaloneo22","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F159488757?v=4","01M7CK5MQXAFZE3W7SAP69KNYR","Carlos Chaparro","01M7CK5MRFE26CDPEQDN5RSQPK",2,"MIT","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint\u002FSKILL.md",[],[],"2026-11-15 14:19:17",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.\ntags: [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,"tags":24,"description":7},[25,26,27,28,29,30,31],"fastapi","python","api","async","pydantic","sqlalchemy","backend","add-x-twitter-scraper-skill","7bc347b2f7dc2dde2761a965585925e0d0171748","cli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint",0,"https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template","https:\u002F\u002Fgithub.com\u002FCarchaloneo22","Ingeniero Informático | Ingeniero en Desarrollo de Software | Consultor TIC en Gestión Publica | Docente Análisis y Desarrollo de Software. ","2026-09-12 11:10:56",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add Carchaloneo22\u002FClaude-Code-template --skill fastapi-endpoint",{"tool":46,"command":47},"bunx","bunx skills add Carchaloneo22\u002FClaude-Code-template --skill fastapi-endpoint",{"tool":49,"command":50},"pnpm","pnpm dlx skills add Carchaloneo22\u002FClaude-Code-template --skill fastapi-endpoint","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-development\u002Ffastapi-endpoint\u002FSKILL.md",true,[],[55,62,71,78,85,92],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M7CPQFVGKX7H3Q5Y9CN0XAZN","zapier-make-patterns","No-code automation democratizes workflow building. Zapier and Make (formerly Integromat) let non-developers automate business processes without writing code. But no-code doesn't mean no-complexity - these platforms have their own patterns, pitfalls, and breaking points.  This skill covers when to use which platform, how to build reliable automations, and when to graduate to code-based solutions. Key insight: Zapier optimizes for simplicity and integrations (7000+ apps), Make optimizes for power","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fzapier-make-patterns\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":66,"licenseFileUrl":67,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7CPQDR2HMKAYHAAY99EA4B2","yeet","Use only when the user explicitly asks to stage, commit, push, and open a GitHub pull request in one flow using the GitHub CLI (`gh`).","Apache-2.0","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7CPQ7K5MAQSXEB027HZFM2G","workflow-automation","Workflow automation is the infrastructure that makes AI agents reliable. Without durable execution, a network hiccup during a 10-step payment flow means lost money and angry customers. With it, workflows resume exactly where they left off.  This skill covers the platforms (n8n, Temporal, Inngest) and patterns (sequential, parallel, orchestrator-worker) that turn brittle scripts into production-grade automation.  Key insight: The platforms make different tradeoffs. n8n optimizes for accessibility","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fworkflow-automation\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7CPQ34F18JHMEM8NHQS1N7K","trigger-dev","Trigger.dev expert for background jobs, AI workflows, and reliable async execution with excellent developer experience and TypeScript-first design. Use when: trigger.dev, trigger dev, background task, ai background job, long running task.","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Ftrigger-dev\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7CPPZSXXDB1SAWT5N63ACZT","planning-with-files","Transforms workflow to use Manus-style persistent markdown files for planning, progress tracking, and knowledge storage. Use when starting complex tasks, multi-step projects, research tasks, or when the user mentions planning, organizing work, tracking progress, or wants structured output.","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fplanning-with-files\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M7CPPTQSBVWSK0R10FJNMP0F","n8n-workflow-patterns","Proven workflow architectural patterns from real n8n workflows. Use when building new workflows, designing workflow structure, choosing workflow patterns, planning workflow architecture, or asking about webhook processing, HTTP API integration, database operations, AI agent workflows, or scheduled tasks.","https:\u002F\u002Fgithub.com\u002FCarchaloneo22\u002FClaude-Code-template\u002Fblob\u002Fadd-x-twitter-scraper-skill\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fworkflow-automation\u002Fn8n\u002Fn8n-workflow-patterns\u002FSKILL.md",[],[]]