Token导航 LogoToken导航

Agent Skill · 开发规范

fastapi-best-practices(FastAPI 最佳实践)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

fastapi-best-practices 是开发规范类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发规范类的 1,265 个 Skill 里排第 430。

总安装 1,738周安装 71GitHub Stars 1下载 562核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:fastapi-best-practices(FastAPI 最佳实践)
来源仓库:https://github.com/ofershap/fastapi-best-practices
仓库路径:skills/fastapi-best-practices
安装命令:
npx skills add https://github.com/ofershap/fastapi-best-practices --skill fastapi-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/ofershap/fastapi-best-practices --skill fastapi-best-practices

这个 Skill 是做什么的

开发规范类 Skill 用来统一代码风格、目录结构和评审口径,产出多为检查清单或改写建议。

用于辅助 Python 项目开发、测试与依赖管理,提供当前最佳实践。强调 async def 优先、类型安全与依赖注入的正确用法。防止常见错误如同步阻塞调用与全局状态滥用。使用时需确认虚拟环境与依赖版本,避免误改生产数据。

fastapi-best-practices 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/fastapi-best-practices

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/ofershap/fastapi-best-practices --skill fastap…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

fastapi-best-practices 怎么安装?

在终端执行 npx skills add https://github.com/ofershap/fastapi-best-practices --skill fastapi-best-pra…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

fastapi-best-practices 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

fastapi-best-practices 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

fastapi-best-practices 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

fastapi-best-practices 用的人多吗?

公开数据是累计安装 1,738 次,近一周安装 71 次,下载 562 次,GitHub 1 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

fastapi-best-practices 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发规范类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发规范类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
vercel-react-best-practices

Vercel React 最佳实践 · Codex、Claude

8,490,72025,918操作浏览器MIT通过
web-design-guidelines

网页设计指南 · Codex、Claude

6,686,01625,885需要联网MIT有提醒
remotion-best-practices

Remotion 最佳实践 · Codex、Claude

6,505,6323,027操作浏览器MIT有提醒
supabase-postgres-best-practices

Supabase Postgres 最佳实践 · Codex、Claude

3,175,5232,030需要联网MIT通过
next-best-practices

Next.js 最佳实践 · Codex、Claude

1,848,240841操作浏览器MIT通过
fastapi-best-practices

FastAPI 最佳实践 · 本页

1,7381需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

When to use

Use this skill when working with FastAPI code. It teaches current best practices and prevents common mistakes that AI agents make with outdated patterns.

Critical Rules

1. Use async def for I/O-bound endpoints, def for CPU-bound

Wrong (agents do this):

@app.get("/users")
def get_users():
    users = db.query(User).all()
    return users

@app.get("/data")
async def get_data():
    result = heavy_computation()
    return result

Correct:

@app.get("/users")
async def get_users(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(User))
    return result.scalars().all()

@app.get("/data")
def get_data():
    return heavy_computation()

Why: FastAPI runs async endpoints in the event loop; sync endpoints run in a thread pool. Use async for I/O (DB, HTTP, file) to avoid blocking. Use def for CPU-bound work; making it async would block the event loop.

2. Use Depends() for dependency injection

Wrong (agents do this):

db = get_database()

@app.get("/items")
async def get_items():
    return db.query(Item).all()

Correct:

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/items")
async def get_items(db: Annotated[Session, Depends(get_db)]):
    return db.query(Item).all()

Why: Global DB connections leak, are not testable, and bypass FastAPI's dependency system. Depends() provides proper scoping, cleanup, and test overrides.

3. Use Pydantic v2 patterns

Wrong (agents do this):

from pydantic import validator

class Item(BaseModel):
    name: str
    price: float

    class Config:
        orm_mode = True

    @validator("price")
    def price_positive(cls, v):
        if v <= 0:
            raise ValueError("must be positive")
        return v

Correct:

from pydantic import BaseModel, field_validator, ConfigDict

class Item(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str
    price: float

    @field_validator("price")
    @classmethod
    def price_positive(cls, v: float) -> float:
        if v <= 0:
            raise ValueError("must be positive")
        return v

Why: Pydantic v1 validator, Config, and orm_mode are deprecated. Use field_validator, model_validator, ConfigDict, and from_attributes.

4. Use lifespan context manager

Wrong (agents do this):

@app.on_event("startup")
async def startup():
    app.state.db = await create_pool()

@app.on_event("shutdown")
async def shutdown():
    await app.state.db.close()

Correct:

from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.db = await create_pool()
    yield
    await app.state.db.close()

app = FastAPI(lifespan=lifespan)

Why: on_event is deprecated. The lifespan context manager gives a single place for startup and shutdown with proper resource ordering.

5. Use BackgroundTasks for fire-and-forget work

Wrong (agents do this):

@app.post("/send-email")
async def send_email(email: str):
    asyncio.create_task(send_email_async(email))
    return {"status": "queued"}

Correct:

@app.post("/send-email")
async def send_email(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email_async, email)
    return {"status": "queued"}

Why: asyncio.create_task can outlive the request and is not awaited on shutdown. BackgroundTasks runs after the response is sent and is tied to the request lifecycle.

6. Use APIRouter for route organization

Wrong (agents do this):

# main.py - 500 lines of routes
@app.get("/users")
@app.get("/users/{id}")
@app.post("/items")
@app.get("/items")

Correct:

# main.py
app.include_router(users.router, prefix="/users", tags=["users"])
app.include_router(items.router, prefix="/items", tags=["items"])

# routers/users.py
router = APIRouter()
@router.get("/")
@router.get("/{id}")

Why: Single-file apps become unmaintainable. APIRouter enables routers/, models/, services/, dependencies/ structure.

7. Use response_model for output validation

Wrong (agents do this):

@app.get("/items/{id}")
async def get_item(id: int):
    item = await db.get(Item, id)
    return {"id": item.id, "name": item.name}

Correct:

@app.get("/items/{id}", response_model=ItemOut)
async def get_item(id: int, db: Session = Depends(get_db)):
    item = await db.get(Item, id)
    if not item:
        raise HTTPException(status_code=404)
    return item

Why: Raw dicts bypass validation and OpenAPI. response_model ensures schema consistency, serialization, and docs.

8. Use status codes from fastapi.status

Wrong (agents do this):

raise HTTPException(status_code=404, detail="Not found")
raise HTTPException(status_code=401, detail="Unauthorized")

Correct:

from fastapi import status

raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Unauthorized")

Why: Magic numbers are error-prone. status constants are self-documenting and match HTTP spec.

9. Use Annotated for dependencies

Wrong (agents do this):

@app.get("/me")
async def read_me(current_user: User = Depends(get_current_user)):
    return current_user

Correct:

@app.get("/me")
async def read_me(current_user: Annotated[User, Depends(get_current_user)]):
    return current_user

Why: Annotated is the recommended FastAPI pattern. It keeps types and dependencies in one place and supports dependency reuse.

10. Use pydantic-settings for configuration

Wrong (agents do this):

import os
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///db.sqlite")

Correct:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str = "sqlite:///db.sqlite"
    debug: bool = False
    model_config = {"env_file": ".env"}

settings = Settings()

Why: os.getenv has no validation or typing. BaseSettings provides validation,.env loading, and type safety.

Patterns

  • Define routers in routers/ with prefix and tags
  • Put shared dependencies in dependencies.py
  • Use HTTPException with status constants for errors
  • Use Path, Query, Body, Header with validation (min_length, ge, le)
  • Register custom exception handlers with app.add_exception_handler
  • Use middleware sparingly; order matters (first added runs last for requests)

Anti-Patterns

  • Do not use @app.on_event("startup") or @app.on_event("shutdown")
  • Do not use asyncio.create_task for request-scoped background work
  • Do not use global variables for DB, cache, or config
  • Do not use Pydantic v1 @validator or class Config
  • Do not return raw dicts without response_model
  • Do not use magic numbers for status codes
  • Do not put all routes in main.py

平台分布

Codex

36.96%
按下载量换算208

Claude

29.07%
按下载量换算163

Cursor

16.72%
按下载量换算94

Gemini CLI

8.5%
按下载量换算48

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills