home / skills / first-fluke / fullstack-starter / fastapi-templates

fastapi-templates skill

/.agents/skills/fastapi-templates

This skill provides production-ready FastAPI project templates and patterns to accelerate starting new services and standardize architecture.

npx playbooks add skill first-fluke/fullstack-starter --skill fastapi-templates

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
2.4 KB
---
name: fastapi-templates
description: Production-ready FastAPI project templates and patterns. Use when starting new FastAPI projects, services, or adding standard components like auth, DB connection, or middleware.
---

# FastAPI Templates

This skill provides production-ready templates and scaffolding patterns for FastAPI applications.

## When to Use

- Starting a new FastAPI service or project.
- Adding standard components (Auth, DB, Logging) to an existing app.
- Standardizing project structure across the team.

## Project Structure Template

Recommended structure for scalable FastAPI apps:

```
src/
├── api/
│   ├── v1/
│   │   ├── endpoints/  # Route handlers
│   │   └── api.py      # Router aggregation
│   └── deps.py         # Dependencies (get_current_user, etc.)
├── core/
│   ├── config.py       # Pydantic BaseSettings
│   └── security.py     # JWT & Password hashing
├── db/
│   ├── models/         # SQLAlchemy models
│   ├── session.py      # DB engine and session factory
│   └── base.py         # Import all models here
├── schemas/            # Pydantic models (Request/Response)
├── services/           # Business logic
└── main.py             # App entrypoint
```

## Code Templates

### 1. Standard API Endpoint

```python
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from src.api import deps
from src.schemas.item import ItemCreate, Item
from src.services import item_service

router = APIRouter()

@router.post("/", response_model=Item)
async def create_item(
    item_in: ItemCreate,
    db: AsyncSession = Depends(deps.get_db),
    current_user = Depends(deps.get_current_user),
) -> Item:
    """
    Create a new item.
    """
    return await item_service.create(db, obj_in=item_in, owner_id=current_user.id)
```

### 2. Pydantic Settings

```python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    PROJECT_NAME: str = "FastAPI App"
    DATABASE_URL: str
    SECRET_KEY: str

    class Config:
        case_sensitive = True
        env_file = ".env"

settings = Settings()
```

### 3. SQLAlchemy Async Model

```python
from sqlalchemy import Column, Integer, String
from src.db.base_class import Base

class Item(Base):
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    description = Column(String, nullable=True)
```

Overview

This skill provides production-ready FastAPI project templates and scaffolding patterns to bootstrap services quickly and consistently. It bundles recommended project layout, example endpoints, Pydantic settings, and async SQLAlchemy models so teams can start with a solid, maintainable foundation. Use it to reduce boilerplate, enforce conventions, and accelerate reliable API development.

How this skill works

The templates define a scalable directory structure (api, core, db, schemas, services, main) and include sample code for common concerns: endpoints, dependency injection, settings management, and async models. It supplies ready-to-use snippets for APIRouter endpoints, Pydantic BaseSettings, and SQLAlchemy async models that integrate with dependency-based DB sessions and authentication. Developers copy or adapt the scaffolding into a new project, then replace the sample components with domain-specific logic.

When to use it

  • Starting a new FastAPI service and wanting a production-ready baseline.
  • Adding standardized components like auth, DB sessions, or config to an existing app.
  • Enforcing a shared project layout and conventions across a team or monorepo.
  • Prototyping an API quickly while retaining patterns suitable for production.

Best practices

  • Keep clear separation: routers in api/, business logic in services/, schemas for validation, and models in db/.
  • Use Pydantic BaseSettings for environment-driven configuration and load .env in non-production.
  • Prefer async SQLAlchemy sessions with dependency-injected DB sessions for request-scoped access.
  • Centralize security helpers (JWT, password hashing) in core/security and guard endpoints with dependency-based current_user.
  • Import all models in db/base to ensure migrations detect them, and use alembic or a migration tool for schema changes.

Example use cases

  • Scaffold a new microservice with auth, DB connection, and standardized endpoints in minutes.
  • Integrate a consistent settings pattern across services to simplify CI/CD and secrets management.
  • Convert a legacy FastAPI app to an opinionated structure for easier maintenance and onboarding.
  • Create a sample endpoint that uses dependency-injected AsyncSession and current_user to enforce ownership.

FAQ

Can I use these templates with synchronous SQLAlchemy?

Yes. The structure is agnostic; swap async session patterns for synchronous sessions and adjust dependency code accordingly.

How do I handle secrets in production?

Keep secrets out of source control, load them via environment variables or a secret manager, and use Pydantic BaseSettings to centralize configuration.