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/error-handling.md

View on GitHub
# Error Handling

## AppException

Custom exception with error codes for frontend handling.

```python
# src/core/exceptions.py
from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from loguru import logger

from src.core.middlewares.request_id_middleware import get_request_id


class AppException(HTTPException):
    """Custom exception with error_code for frontend"""

    def __init__(self, status_code: int, message: str, error_code: str | None = None):
        super().__init__(status_code=status_code, detail=message)
        self.error_code = error_code
```

## Exception Handlers

```python
# src/core/exceptions.py
def register_exception_handlers(app: FastAPI) -> None:
    """Register global exception handlers"""

    @app.exception_handler(HTTPException)
    async def http_exception_handler(
        request: Request, exc: HTTPException
    ) -> JSONResponse:
        """Handle HTTP exceptions with standardized format"""
        request_id = get_request_id()

        status_code = exc.status_code
        message = exc.detail
        error_code = getattr(exc, "error_code", None)

        logger.error(
            f"[{request_id}] HTTPException: {status_code} - {message}",
            extra={
                "request_id": request_id,
                "status_code": status_code,
                "error_code": error_code,
            },
        )

        return JSONResponse(
            status_code=status_code,
            content={
                "request_id": request_id,
                "message": message,
                "error_code": error_code,
            },
        )

    @app.exception_handler(Exception)
    async def catch_all_exception_handler(
        request: Request, exc: Exception
    ) -> JSONResponse:
        """Catch unhandled exceptions"""
        request_id = get_request_id()

        logger.error(
            f"[{request_id}] Unhandled: {exc.__class__.__name__}",
            extra={
                "request_id": request_id,
                "exception_type": exc.__class__.__name__,
                "exception_message": str(exc),
            },
        )

        return JSONResponse(
            status_code=500,
            content={
                "request_id": request_id,
                "message": "Internal server error",
                "error_code": None,
            },
        )
```

## Registration

```python
# src/main.py
from src.core.exceptions import register_exception_handlers

app = FastAPI()
register_exception_handlers(app)
```

## Error Codes

Define error codes per module:

```python
# src/modules/auth/auth_constants.py
class AuthErrorCode:
    USER_EXISTED = "user_existed"
    INVALID_CREDENTIALS = "invalid_credentials"
    ACCOUNT_INACTIVE = "account_inactive"


# src/modules/users/user_constants.py
class UserErrorCode:
    USER_NOT_FOUND = "user_not_found"
    CANNOT_SELF_MODIFY = "cannot_self_modify"
```

## Using in Services

```python
from src.core.exceptions import AppException
from src.modules.auth.auth_constants import AuthErrorCode


async def register_user(db: AsyncSession, data: RegisterRequest) -> User:
    existing = await get_user_by_email(db, data.email)
    if existing:
        raise AppException(400, "Email already registered", AuthErrorCode.USER_EXISTED)
    ...


async def authenticate_user(db: AsyncSession, email: str, password: str) -> User:
    user = await get_user_by_email(db, email)
    if not user:
        raise AppException(401, "Invalid email or password")

    if not user.is_active:
        raise AppException(403, "Account is inactive", AuthErrorCode.ACCOUNT_INACTIVE)
    ...
```

## Response Format

**Success:**
```json
{
  "data": { ... },
  "message": null
}
```

**Error:**
```json
{
  "request_id": "req_abc123xyz",
  "message": "Email already registered",
  "error_code": "user_existed"
}
```

## HTTP Status Codes

| Status | Use Case |
|--------|----------|
| 400 | Bad request, validation error |
| 401 | Authentication required |
| 403 | Forbidden (authenticated but not authorized) |
| 404 | Resource not found |
| 409 | Conflict (duplicate resource) |
| 422 | Validation error (Pydantic) |
| 500 | Internal server error |

## Frontend Integration

Frontend can use `error_code` for:
- Displaying localized messages
- Conditional UI logic
- Form field highlighting

```typescript
// Frontend example
if (error.error_code === "user_existed") {
  setFieldError("email", "This email is already registered");
}
```

## Best Practices

1. **Always include request_id** - For debugging and support
2. **Use error codes** - Machine-readable for frontend
3. **Generic 500 message** - Never expose internal errors
4. **Log all errors** - With request_id for tracing
5. **Consistent format** - Same structure for all errors
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 318kUpdated 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