Skip to content

avibebuilder/claude-prime / .claude/starter-skills/backend-fastapi-python

backend-fastapi-python

Verified

Use this skill for any Python backend work in this project: building FastAPI endpoints, writing service functions, defining Pydantic/SQLModel schemas, running Alembic migrations, or debugging 422 errors. Essential for authentication and authorization patterns — setting up get_current_user, is_superuser checks, admin-only guards, role-based access, and dependency injection chains like Depends(). Also covers middleware, background tasks, async SQLAlchemy sessions, ORM relationship loading, and request/response design. Activate whenever the question involves Python API code, FastAPI patterns, or backend architecture in this codebase. Not for frontend, Docker, CI/CD, or infrastructure.

FileKindSize
SKILL.mdskill md3.9 KB
references/auth.mdmarkdown5.5 KB
references/configuration.mdmarkdown3.5 KB
references/database.mdmarkdown3.9 KB
references/dependencies.mdmarkdown4.4 KB
references/error-handling.mdmarkdown4.7 KB
references/file-structure.mdmarkdown3.8 KB
references/middleware.mdmarkdown4.9 KB
references/models.mdmarkdown3.9 KB
references/routing.mdmarkdown4.5 KB
references/schemas.mdmarkdown4.3 KB
references/services.mdmarkdown5.1 KB

references/dependencies.md

View on GitHub
# Dependencies

## FastAPI Dependency Injection

Dependencies are reusable components injected into routes using `Depends()`.

## Database Dependency

```python
# src/core/database.py
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_maker() as session:
        yield session
```

Usage:
```python
@router.get("/users")
async def list_users(db: AsyncSession = Depends(get_db)):
    ...
```

## Authentication Dependencies

Build composable auth chain:

```python
# src/modules/auth/auth_dependencies.py
from fastapi import Depends, Request
from jose import JWTError
from sqlalchemy.ext.asyncio import AsyncSession

from src.core.database import get_db
from src.core.exceptions import AppException
from src.models.user_model import User
from src.modules.auth.auth_service import get_user_by_id
from src.modules.auth.auth_utils import decode_token


async def get_current_user(
    request: Request,
    db: AsyncSession = Depends(get_db),
) -> User | None:
    """Optional auth - returns None if no valid token"""
    access_token = request.cookies.get("access_token")
    if not access_token:
        return None

    try:
        payload = decode_token(access_token)
        user_id = payload.get("sub")

        if not user_id or not isinstance(user_id, str):
            return None

        user = await get_user_by_id(db, user_id)
        if not user or not user.is_active:
            return None

        return user
    except (JWTError, Exception):
        return None


async def require_auth(
    user: User | None = Depends(get_current_user),
) -> User:
    """Required auth - raises 401 if no user"""
    if not user:
        raise AppException(401, "Authentication required")
    return user


async def require_admin(
    user: User = Depends(require_auth),
) -> User:
    """Required admin - raises 403 if not admin"""
    if not user.is_admin:
        raise AppException(403, "Admin access required")
    return user
```

## Dependency Chain

```
get_current_user (optional)
       ↓
  require_auth (required)
       ↓
  require_admin (admin only)
```

## Using in Routes

```python
# Optional auth - user might be None
@router.get("/public")
async def public_endpoint(
    user: User | None = Depends(get_current_user),
):
    if user:
        # Logged in user
        ...
    else:
        # Anonymous user
        ...


# Required auth
@router.get("/me")
async def get_profile(
    user: User = Depends(require_auth),
):
    return ApiResponse(data=user)


# Admin only
@router.get("/users")
async def list_users(
    admin: User = Depends(require_admin),
    db: AsyncSession = Depends(get_db),
):
    # Only admins reach here
    ...


# Unused dependency (for side effects like auth check)
@router.delete("/users/{user_id}")
async def delete_user(
    user_id: str,
    _admin: User = Depends(require_admin),  # Underscore = unused
    db: AsyncSession = Depends(get_db),
):
    ...
```

## Custom Dependencies

### Query Parameters

```python
from fastapi import Query
from pydantic import BaseModel


class PaginationParams(BaseModel):
    page: int = 1
    limit: int = 20


def pagination(
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
) -> PaginationParams:
    return PaginationParams(page=page, limit=limit)


@router.get("/items")
async def list_items(pagination: PaginationParams = Depends(pagination)):
    offset = (pagination.page - 1) * pagination.limit
    ...
```

### Resource Ownership

```python
async def get_own_post(
    post_id: str,
    user: User = Depends(require_auth),
    db: AsyncSession = Depends(get_db),
) -> Post:
    post = await post_service.get_by_id(db, post_id)
    if not post:
        raise AppException(404, "Post not found")
    if post.user_id != user.id:
        raise AppException(403, "Not your post")
    return post


@router.patch("/posts/{post_id}")
async def update_post(
    data: UpdatePostRequest,
    post: Post = Depends(get_own_post),
    db: AsyncSession = Depends(get_db),
):
    ...
```

## Best Practices

1. **Chain dependencies** - Build on top of each other
2. **Single responsibility** - One dependency, one concern
3. **Use `_` prefix** - For unused but required dependencies
4. **Return domain objects** - Not raw data
5. **Raise AppException** - Consistent error handling
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 319kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 117kUpdated Claude CodeCodexVerifiedInstall