Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

fastapi-patterns

БесплатноБез исполняемых скриптовНе проверен

FastAPI best practices, Pydantic models, SQLAlchemy ORM, async patterns, dependency injection, and JWT authentication. Activate for FastAPI apps, async Python…

TheLobbiот TheLobbi★ 22 звезды на GitHub

Об этом скилле

FastAPI Patterns Skill

Provides comprehensive FastAPI development patterns and best practices for building modern, production-ready Python APIs.

When to Use This Skill

Activate this skill when working with:

  • FastAPI application architecture and design
  • Pydantic models and data validation
  • SQLAlchemy ORM patterns and relationships
  • Async/await patterns and performance optimization
  • Dependency injection and middleware
  • JWT authentication and authorization
  • API documentation and OpenAPI schemas

Quick Reference

Development Commands

# Development server with auto-reload
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Production with workers
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

# With Gunicorn (recommended for production)
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000

# Install dependencies
pip install fastapi uvicorn[standard] sqlalchemy pydantic-settings python-jose passlib bcrypt

# Run tests
pytest tests/ -v --cov=app

Application Structure

app/
├── main.py                 # Application entry point
├── config.py              # Settings and configuration
├── dependencies.py        # Dependency injection
├── database.py           # Database connection
├── models/               # SQLAlchemy models
│   ├── __init__.py
│   ├── user.py
│   ├── organization.py
│   └── base.py
├── schemas/              # Pydantic schemas
│   ├── __init__.py
│   ├── user.py
│   └── organization.py
├── routers/              # API endpoints
│   ├── __init__.py
│   ├── auth.py
│   ├── users.py
│   └── organizations.py
├── services/             # Business logic
│   ├── __init__.py
│   ├── auth_service.py
│   └── user_service.py
├── middleware/           # Custom middleware
│   └── auth.py
└── utils/               # Utility functions
    ├── security.py
    └── validators.py

Application Setup with Lifespan

# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import create_async_engine

from app.config import settings
from app.routers import auth, users, organizations
from app.database import init_db

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: Initialize database connection
    await init_db()
    print("Database initialized")
    yield
    # Shutdown: Close connections
    print("Shutting down...")

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    lifespan=lifespan
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(auth.router, prefix=f"{settings.API_V1_STR}/auth", tags=["auth"])
app.include_router(users.router, prefix=f"{settings.API_V1_STR}/users", tags=["users"])
app.include_router(organizations.router, prefix=f"{settings.API_V1_STR}/organizations", tags=["organizations"])

@app.get("/health")
async def health_check():
    return {"status": "healthy", "version": settings.VERSION}

Pydantic Settings and Configuration

# config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing import List

class Settings(BaseSettings):
    # Application
    PROJECT_NAME: str = "Zenith API"
    VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"

    # Database
    DATABASE_URL: str
    DB_POOL_SIZE: int = 10
    DB_MAX_OVERFLOW: int = 20

    # Security
    SECRET_KEY: str
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    REFRESH_TOKEN_EXPIRE_DAYS: int = 7

    # CORS
    ALLOWED_ORIGINS: List[str] = ["http://localhost:3000"]

    # Redis
    REDIS_URL: str = "redis://localhost:6379"

    model_config = SettingsConfigDict(
        env_file=".env",
        case_sensitive=True
    )

settings = Settings()

SQLAlchemy Models with Async

# models/base.py
from sqlalchemy.ext.asyncio import AsyncAttrs
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from datetime import datetime

class Base(AsyncAttrs, DeclarativeBase):
    pass

class TimestampMixin:
    created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)

# models/user.py
from sqlalchemy import String, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, TimestampMixin

class User(Base, TimestampMixin):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
    hashed_password: Mapped[str] = mapped_column(String(255))
    full_name: Mapped[str] = mapped_column(String(255))
    is_active: Mapped[bool] = mapped_column(Boole
Полный SKILL.md на GitHub

Установить fastapi-patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Bash
Read
Write
Edit
Glob
Grep

FAQ

Что делает скилл fastapi-patterns?

FastAPI best practices, Pydantic models, SQLAlchemy ORM, async patterns, dependency injection, and JWT authentication. Activate for FastAPI apps, async Python APIs, API design, and modern Python web services.

Как установить скилл fastapi-patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл fastapi-patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить fastapi-patterns с