avibebuilder/claude-prime / .claude/starter-skills/backend-fastapi-python
backend-fastapi-python
UnverifiedUse 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.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.9 KB |
| references/auth.md | markdown | 5.5 KB |
| references/configuration.md | markdown | 3.5 KB |
| references/database.md | markdown | 3.9 KB |
| references/dependencies.md | markdown | 4.4 KB |
| references/error-handling.md | markdown | 4.7 KB |
| references/file-structure.md | markdown | 3.8 KB |
| references/middleware.md | markdown | 4.9 KB |
| references/models.md | markdown | 3.9 KB |
| references/routing.md | markdown | 4.5 KB |
| references/schemas.md | markdown | 4.3 KB |
| references/services.md | markdown | 5.1 KB |
references/models.md
View on GitHub# Models
## SQLModel Overview
SQLModel combines SQLAlchemy and Pydantic. Models serve as both ORM entities and data validation.
## Base Model
Define a base class with common fields:
```python
# src/models/base_model.py
from datetime import UTC, datetime
from sqlalchemy import Column, DateTime
from sqlmodel import Field, SQLModel
from src.core.utils import generate_id
class BaseSQLModel(SQLModel):
id: str = Field(default_factory=generate_id, primary_key=True, index=True)
created_at: datetime = Field(
default_factory=lambda: datetime.now(UTC),
sa_column=Column(DateTime(timezone=True), nullable=False),
)
updated_at: datetime = Field(
default_factory=lambda: datetime.now(UTC),
sa_column=Column(
DateTime(timezone=True),
nullable=False,
onupdate=lambda: datetime.now(UTC),
),
)
```
### ID Generation
```python
# src/core/utils.py
from nanoid import generate as _nanoid_generate
NANOID_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def generate_id(size: int = 14) -> str:
"""Generate alphanumeric ID using nanoid with custom alphabet"""
return _nanoid_generate(alphabet=NANOID_ALPHABET, size=size)
```
## Entity Models
```python
# src/models/user_model.py
from datetime import datetime
from typing import Literal
from sqlalchemy import ARRAY, Column, DateTime, String
from sqlmodel import Field
from src.models.base_model import BaseSQLModel
AuthProvider = Literal["email", "google"]
class User(BaseSQLModel, table=True):
__tablename__ = "users"
# Required fields
first_name: str
last_name: str
email: str = Field(unique=True, index=True)
# Authentication
hashed_password: str | None = None
auth_providers: list[str] = Field(
sa_column=Column(ARRAY(String), nullable=False, server_default='{"email"}')
)
google_id: str | None = Field(default=None, unique=True, index=True)
# Profile
avatar_url: str | None = None
# Permissions
is_active: bool = True
is_admin: bool = False
# Analytics
last_sign_in_at: datetime | None = Field(
default=None, sa_column=Column(DateTime(timezone=True), nullable=True)
)
# Computed properties
@property
def full_name(self) -> str:
return f"{self.first_name} {self.last_name}"
```
## Field Patterns
### Required vs Optional
```python
# Required - no default
first_name: str
# Optional with default
avatar_url: str | None = None
is_active: bool = True
```
### Unique and Indexed
```python
email: str = Field(unique=True, index=True)
google_id: str | None = Field(default=None, unique=True, index=True)
```
### Array Fields (PostgreSQL)
```python
from sqlalchemy import ARRAY, Column, String
auth_providers: list[str] = Field(
sa_column=Column(ARRAY(String), nullable=False, server_default='{"email"}')
)
```
### DateTime with Timezone
```python
from sqlalchemy import Column, DateTime
last_sign_in_at: datetime | None = Field(
default=None,
sa_column=Column(DateTime(timezone=True), nullable=True)
)
```
### Auto-update Timestamp
```python
updated_at: datetime = Field(
default_factory=lambda: datetime.now(UTC),
sa_column=Column(
DateTime(timezone=True),
nullable=False,
onupdate=lambda: datetime.now(UTC),
),
)
```
## Model Export
Export all models from `__init__.py` for Alembic:
```python
# src/models/__init__.py
from src.models.base_model import BaseSQLModel
from src.models.user_model import User
__all__ = ["BaseSQLModel", "User"]
```
## Best Practices
1. **Always inherit from `BaseSQLModel`** - Consistent id, created_at, updated_at
2. **Use `table=True`** - Required for ORM mapping
3. **Set `__tablename__`** - Explicit table name
4. **Use timezone-aware datetime** - `DateTime(timezone=True)`
5. **Index frequently queried fields** - `Field(index=True)`
6. **Use properties for computed values** - Not stored in DB
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 318k | Updated | Claude CodeCodex | Unverified | Install |
| 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: 196k | Updated | Claude CodeCodex | Verified | Install |
| 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: 118k | Updated | Claude CodeCodex | Verified | Install |
| 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: 117k | Updated | Claude CodeCodex | Unverified | Install |