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/schemas.md

View on GitHub
# Schemas

## Pydantic Schemas for API

Schemas define request/response shapes. Separate from SQLModel entities.

## Core Schemas

```python
# src/core/schemas.py
from pydantic import BaseModel, Field, computed_field


class ApiResponse[T](BaseModel):
    """Generic API response wrapper"""
    data: T | None = None
    message: str | None = None


class PaginationParams(BaseModel):
    """Pagination query parameters"""
    page: int = Field(default=1, ge=1, description="Page number")
    limit: int = Field(default=20, ge=1, le=100, description="Items per page")


class CommonQueryParams(PaginationParams):
    """Common query parameters with search and sort"""
    q: str | None = Field(default=None, description="Search query")
    sort_by: list[str] = Field(
        default_factory=list,
        description="Sort fields with direction (e.g., 'name:asc', 'created_at:desc')",
    )


class PaginatedResponse[T](BaseModel):
    """Paginated list response"""
    items: list[T]
    total: int
    page: int
    limit: int

    @computed_field
    @property
    def total_pages(self) -> int:
        return (self.total + self.limit - 1) // self.limit
```

## Request Schemas

Naming: `{Action}Request`

```python
# src/modules/auth/auth_schemas.py
from pydantic import BaseModel, EmailStr, Field


class RegisterRequest(BaseModel):
    email: EmailStr
    password: str = Field(min_length=8)
    first_name: str
    last_name: str


class LoginRequest(BaseModel):
    email: EmailStr
    password: str


class UpdateUserRequest(BaseModel):
    """Partial update - all fields optional"""
    first_name: str | None = None
    last_name: str | None = None
    is_active: bool | None = None
    is_admin: bool | None = None
```

## Response Schemas

Naming: `{Entity}Response`

```python
# src/modules/auth/auth_schemas.py
from pydantic import BaseModel


class AuthUserResponse(BaseModel):
    model_config = {"from_attributes": True}  # Enable ORM mode

    id: str
    email: str
    first_name: str
    last_name: str
    full_name: str  # Property from model
    is_admin: bool


class UserResponse(BaseModel):
    model_config = {"from_attributes": True}

    id: str
    email: str
    first_name: str
    last_name: str
    full_name: str
    is_active: bool
    is_admin: bool
    created_at: datetime
```

## Using in Routes

```python
from src.core.schemas import ApiResponse, PaginatedResponse
from src.modules.users.user_schemas import UserResponse


@router.get("", response_model=ApiResponse[PaginatedResponse[UserResponse]])
async def list_users(
    page: int = Query(1, ge=1),
    limit: int = Query(20, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
) -> ApiResponse[PaginatedResponse[UserResponse]]:
    users, total = await user_service.list_users(db, page, limit)

    return ApiResponse(
        data=PaginatedResponse(
            items=users,
            total=total,
            page=page,
            limit=limit,
        )
    )


@router.post("/register", response_model=ApiResponse[AuthUserResponse])
async def register(
    data: RegisterRequest,
    db: AsyncSession = Depends(get_db),
) -> ApiResponse[User]:
    user = await auth_service.register_user(db, data)
    return ApiResponse(data=user)
```

## Key Patterns

### ORM Mode

```python
class UserResponse(BaseModel):
    model_config = {"from_attributes": True}  # Pydantic v2
    # Allows: UserResponse.model_validate(user_orm_object)
```

### Partial Updates

```python
class UpdateUserRequest(BaseModel):
    # All optional for PATCH
    first_name: str | None = None
    last_name: str | None = None
```

### Validation

```python
from pydantic import EmailStr, Field

email: EmailStr  # Email validation
password: str = Field(min_length=8)  # Length constraint
page: int = Field(ge=1)  # Greater than or equal
limit: int = Field(ge=1, le=100)  # Range
```

### Generic Types (Python 3.12+)

```python
class ApiResponse[T](BaseModel):
    data: T | None = None

# Usage
ApiResponse[UserResponse]
ApiResponse[PaginatedResponse[UserResponse]]
```

## Best Practices

1. **Separate request/response schemas** - Don't reuse models
2. **Use `from_attributes=True`** - For ORM to Pydantic conversion
3. **Validate at boundaries** - Request schemas validate input
4. **Explicit response shapes** - Response schemas define output
5. **Generic wrapper** - `ApiResponse[T]` for consistency
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: 118kUpdated Claude CodeCodexVerifiedInstall