fastapi
Skill4 starsChanged 7 months agoMITView on GitHub
Load this file when working on a FastAPI project. Use alongside all skills/common/ files.
16 other projects use a version of this.
Adopted by
Most recently taken up by
- jawwad-ali/claude-code-skillstheir own version, first seen Sep 5, 2026
- Spardutti/claude-skillstheir own version, first seen Aug 31, 2026
- peakdong68/my-skillstheir own version, first seen Aug 29, 2026
- conjure-3301/skillstheir own version, first seen Aug 17, 2026
- Bbar0n234/learnflow-aitheir own version, first seen Aug 11, 2026
- youlaitech/youlai-skillstheir own version, first seen Jul 14, 2026
Used with
Projects with it also use react and docker.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
VercelSkillreact
React renderer for json-render that turns JSON specs into React components. Use when working with @json-render/react, building React UIs from JSON, creating component catalogs, or rendering AI-generated specs.
Also in 3 projects that use this
akornmeierSkilldocker
Guide for using Docker - a containerization platform for building, running, and deploying applications in isolated containers. Use when containerizing applications, creating Dockerfiles, working with Docker Compose, managing images/containers, configuring networking and storage, optimizing builds, deploying to production, or implementing CI/CD pipelines with Docker.
Also in 3 projects that use this
Other versions16 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 16
- youlaitech/youlai-skills★ 56same name
- martinholovsky/claude-skills-generator★ 47same name
- Bbar0n234/learnflow-ai★ 35same name
- nimadorostkar/Claude-Skills-collection★ 28same name
- sordi-ai/skill-everything★ 20same name
- DongDuong2001/pudo-code-system★ 5same name
- jawwad-ali/claude-code-skills★ 4same name
- Spardutti/claude-skills★ 3same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- aptitude-stack/registery★ 1same name
6 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository11 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/python-core.mdcCursor rule
- .cursor/rules/python-security.mdcCursor rule
- .cursor/rules/python-testing.mdcCursor rule
- llms.txtllms.txt
- python-standardsSkill
- djangoSkill
- drfSkill
- flaskSkill
The file
We split this skill into the rules it gives an agent
4 rules. 0 are common, 1 is distinctive, and 3 are very specific to this project.
0
Common
Most of the 14 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 219
Every service must expose:
- Very specific: line 233
Always use the lifespan context manager:
- Very specific: line 287
All routes receive a Pydantic request model (or query params for GETs) and return a Pydantic response model.
- Very specific: line 288
Never accept dict or return dict from a route.
“Common” is measured: kept by at least 6 in 10 of the 14 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
FastAPI Skill
Load this file when working on a FastAPI project. Use alongside all
skills/common/files.
Stack
| Layer | Library |
| Framework | FastAPI 0.111+ |
| ASGI Server | Uvicorn with Gunicorn workers (prod) |
| ORM | SQLAlchemy 2.x async + Alembic |
| Validation | Pydantic v2 |
| Auth | python-jose / PyJWT + passlib |
| HTTP Client | httpx (async) |
| Task Queue | Celery + Redis (or ARQ for lighter workloads) |
| Settings | pydantic-settings |
Project Structure (FastAPI-specific additions)
app/
├── main.py ← App factory: create_app()
├── core/
│ ├── config.py
│ ├── security.py
│ ├── exceptions.py
│ └── logging.py
├── api/
│ ├── deps.py ← Shared FastAPI dependencies
│ ├── v1/
│ │ ├── __init__.py
│ │ ├── router.py ← Aggregates all v1 routers
│ │ ├── users.py
│ │ ├── auth.py
│ │ └── health.py
├── models/ ← SQLAlchemy ORM models
├── schemas/ ← Pydantic request/response models
├── repositories/
├── services/
└── workers/ ← Background task definitionsApp Factory Pattern
# app/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.core.logging import configure_logging
from app.core.exceptions import AppBaseException, app_exception_handler
from app.api.v1.router import v1_router
def create_app() -> FastAPI:
"""Application factory."""
configure_logging(log_level=settings.log_level, json_logs=not settings.debug)
app = FastAPI(
title=settings.app_name,
version=settings.app_version,
docs_url="/docs" if settings.debug else None, # hide Swagger in prod
redoc_url="/redoc" if settings.debug else None,
)
app.add_middleware(CORSMiddleware, allow_origins=settings.allowed_origins, ...)
app.add_exception_handler(AppBaseException, app_exception_handler)
app.include_router(v1_router, prefix="/api/v1")
return app
app = create_app()Dependency Injection
# app/api/deps.py
from fastapi import Depends, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_session
from app.core.security import decode_token
from app.repositories.user_repository import UserRepository
from app.services.user_service import UserService
bearer_scheme = HTTPBearer()
async def get_db() -> AsyncSession:
async with get_session() as session:
yield session
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Security(bearer_scheme),
session: AsyncSession = Depends(get_db),
) -> User:
payload = decode_token(credentials.credentials)
repo = UserRepository(session)
user = await repo.find_by_id(int(payload["sub"]))
if not user or not user.is_active:
raise AuthenticationError()
return userRouter + Endpoint Pattern
# app/api/v1/users.py
from fastapi import APIRouter, Depends, status
from app.api.deps import get_current_user, get_db
from app.schemas.user import UserCreateRequest, UserResponse, UserListResponse
from app.services.user_service import UserService
router = APIRouter(prefix="/users", tags=["Users"])
@router.get("/", response_model=UserListResponse)
async def list_users(
page: int = 1,
page_size: int = 20,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_db),
) -> UserListResponse:
"""List all users with pagination."""
service = UserService(UserRepository(session))
return await service.list_users(page=page, page_size=page_size)
@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
data: UserCreateRequest,
session: AsyncSession = Depends(get_db),
) -> UserResponse:
"""Create a new user account."""
service = UserService(UserRepository(session))
return await service.create_user(data)Pydantic Schemas
# app/schemas/user.py
from pydantic import BaseModel, ConfigDict, Field
from datetime import datetime
class UserBase(BaseModel):
email: str
name: str
class UserCreateRequest(UserBase):
password: str = Field(min_length=8)
class UserResponse(UserBase):
model_config = ConfigDict(from_attributes=True) # enables ORM mode
id: int
is_active: bool
created_at: datetime
class UserListResponse(BaseModel):
items: list[UserResponse]
total: int
page: int
page_size: intDatabase Session
# app/core/database.py
from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.core.config import settings
engine = create_async_engine(settings.database_url, pool_pre_ping=True, echo=settings.debug)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_session() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raiseBackground Tasks
For CPU-light tasks: use FastAPI BackgroundTasks.
For heavy/reliable tasks: use Celery.
# Lightweight (email sending, audit logging)
@router.post("/users/")
async def create_user(data: UserCreateRequest, background_tasks: BackgroundTasks):
user = await service.create_user(data)
background_tasks.add_task(send_welcome_email, user.email)
return userHealth Check Endpoint
Every service must expose:
@router.get("/health", include_in_schema=False)
async def health_check(session: AsyncSession = Depends(get_db)) -> dict:
await session.execute(text("SELECT 1"))
return {"status": "ok", "version": settings.app_version}LIFESPAN CONTEXT MANAGER (replaces deprecated @app.on_event)
@app.on_event("startup") and @app.on_event("shutdown") are deprecated since FastAPI 0.93.
Always use the lifespan context manager:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup — runs once before the app begins accepting requests
await db_pool.connect()
configure_logging(json_output=not settings.debug)
logger.info("app_started", version=settings.app_version)
yield # application runs here
# Shutdown — runs once after the last request is handled
await db_pool.disconnect()
logger.info("app_stopped")
def create_app() -> FastAPI:
return FastAPI(lifespan=lifespan, ...)ANNOTATED DEPENDENCIES (Python 3.9+)
Define reusable dependency annotations at module level for cleaner route signatures:
from typing import Annotated
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
# Define once in deps.py
DbSession = Annotated[AsyncSession, Depends(get_db)]
CurrentUser = Annotated[User, Depends(get_current_user)]
AdminUser = Annotated[User, Depends(require_admin)]
# Use cleanly in every route
@router.get("/orders/", response_model=OrderListResponse)
async def list_orders(
db: DbSession,
current_user: CurrentUser,
page: int = 1,
) -> OrderListResponse:
...RORO IN FASTAPI ROUTES
All routes receive a Pydantic request model (or query params for GETs) and return a Pydantic response model.
Never accept dict or return dict from a route.
# CORRECT — RORO
@router.post("/orders/", response_model=OrderResponse, status_code=201)
async def create_order(data: OrderCreate, db: DbSession, user: CurrentUser) -> OrderResponse:
return await order_service.create_order(user_id=user.id, data=data)
# WRONG — raw dict in, raw dict out
@router.post("/orders/")
async def create_order(request: Request) -> dict:
body = await request.json()
...Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

