后端写作
- 作者仓库星标 98,864
- 作者更新于 实时读取
- 作者仓库 fastapi
- 领域
- AI 智能
- 兼容 Agent
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- 信任分
- 88 / 100 · 社区维护
- 作者 / 版本 / 许可
- @fastapi · 未声明 license
- Token 消耗评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部 API Key
- 需要 · Vendor-specific
- 兼容的系统
- 未声明(默认跨平台)
- 底层运行要求
- Python
- 文件与系统权限
-
- 只读
- 允许写入 / 修改
- 网络行为
- 允许外网请求
- 安装命令数
- 26 条
档案由构建时根据 SKILL.md 与安装命令自动衍生,可能与作者实际意图存在差异。
需要注意: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: fastapi
description: FastAPI best practices and conventions. Use when working with FastAPI APIs and Pydantic models f…
category: AI 智能
runtime: Python
---
# fastapi 输出预览
## PART A: 任务判断
- 适用问题:提示词、Agent 工作流、模型评估或自动化推理。
- 输入要求:目标材料、限制条件、期望输出和验收方式。
- 证据边界:围绕“Use the fastapi CLI / Add an entrypoint in pyproject.toml / Use fastapi with a path”读取原文规则,不把推断写成作者承诺。
## PART B: 执行结果
- **01** 任务判断:确认你的需求是否属于提示词、Agent 工作流、模型评估或自动化推理,并标出输入、限制和预期结果。
- **02** 执行计划:优先按“Use the fastapi CLI / Add an entrypoint in pyproject.toml / Use fastapi with a path”拆成步骤,说明每一步会读取什么、修改什么、产出什么。
- **03** 交付结果:给出可复制的命令、文件改动、检查清单或内容草稿,并说明如何继续迭代。
- **04** 风险边界:结合 读取文件、写入/修改文件、会按任务需要访问外部网络、需要准备 Vendor-specific API Key 给出执行前确认项。
## Running Rules
- 读取文件、写入/修改文件;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先小样例验证,再放大到真实任务。
- 交付时同时给结果、检查口径和下一步迭代建议。 原文没有稳定的斜杠命令要求。安装验证后通常全局生效,直接在对话里点名这个 Skill 并描述任务即可。
告诉 Agent 目标文件或材料、期望结果、不可改范围、是否允许联网或执行命令。本 Skill 的权限画像是:读取文件、写入/修改文件。
先用一个小任务确认它会围绕“Use the fastapi CLI / Add an entrypoint in pyproject.toml / Use fastapi with a path”工作;涉及文件或命令时,先看 diff、日志、预览或测试结果。
检查最终产物是否包含明确结果、必要证据和下一步动作;如果输出泛泛而谈,就补充输入、边界和验收标准后重跑。
---
name: fastapi
description: FastAPI best practices and conventions. Use when working with FastAPI APIs and Pydantic models f…
category: AI 智能
source: fastapi/fastapi
---
# fastapi
## 什么时候使用
- 用于组织测试、定位失败并形成修复闭环 适合处理AI Agent、提示词、模型评估与自动化推理,核心价值是把输入、判断、执行、验证和交付边界固定下来,避免 Agent 泛泛回答。 把任务拆成可执行、可检查、可继续迭代的步骤;使用前要准备…
- 面向提示词、Agent 工作流、模型评估或自动化推理,优先处理能明确输入、步骤和验收标准的工作。
## 需要提供什么
- 目标材料、目录范围、期望结果和不可改动内容。
- 是否允许联网、执行命令、读写文件或调用外部服务。
## 执行规则
- 围绕「Use the fastapi CLI / Add an entrypoint in pyproject.toml / Use fastapi with a path」组织步骤,不把推断写成作者事实。
- 读取文件、写入/修改文件;会按任务需要访问外部网络;需要准备 Vendor-specific API Key。
- 先跑小样例,确认结果可检查后再扩大任务范围。
## 输出要求
- 给出最终产物、关键证据、验证方式和下一步动作。
- 信息不足时标记 unknown,不编造命令、平台或依赖。 作者原文负责流程事实;仓库文件负责来源和命令;流狐只补充适用场景、限制和质量判断。
skill "fastapi" {
输入层 -> 用户目标 + 目标文件 + 禁止范围 + 验收标准
上下文层 -> Use the fastapi CLI / Add an entrypoint in pyproject.toml / Use fastapi with a path
规则层 -> SKILL.md 触发条件 / 执行顺序 / 输出格式
运行层 -> Python | 读取文件、写入/修改文件 | 会按任务需要访问外部网络
安全层 -> 需要准备 Vendor-specific API Key + 小任务验证 + diff / 日志复核
输出层 -> 可复制结果 + 检查清单 + 下一步迭代
} FastAPI
Official FastAPI skill to write code with best practices, keeping up to date with new versions and features.
Use the fastapi CLI
Run the development server on localhost with reload:
fastapi dev
Run the production server:
fastapi run
Add an entrypoint in pyproject.toml
FastAPI CLI will read the entrypoint in pyproject.toml to know where the FastAPI app is declared.
[tool.fastapi]
entrypoint = "my_app.main:app"
Use fastapi with a path
When adding the entrypoint to pyproject.toml is not possible, or the user explicitly asks not to, or it's running an independent small app, you can pass the app file path to the fastapi command:
fastapi dev my_app/main.py
Prefer to set the entrypoint in pyproject.toml when possible.
Use Annotated
Always prefer the Annotated style for parameter and dependency declarations.
It keeps the function signatures working in other contexts, respects the types, allows reusability.
In Parameter Declarations
Use Annotated for parameter declarations, including Path, Query, Header, etc.:
from typing import Annotated
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(
item_id: Annotated[int, Path(ge=1, description="The item ID")],
q: Annotated[str | None, Query(max_length=50)] = None,
):
return {"message": "Hello World"}
instead of:
# DO NOT DO THIS
@app.get("/items/{item_id}")
async def read_item(
item_id: int = Path(ge=1, description="The item ID"),
q: str | None = Query(default=None, max_length=50),
):
return {"message": "Hello World"}
For Dependencies
Use Annotated for dependencies with Depends().
Unless asked not to, create a new type alias for the dependency to allow re-using it.
from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
def get_current_user():
return {"username": "johndoe"}
CurrentUserDep = Annotated[dict, Depends(get_current_user)]
@app.get("/items/")
async def read_item(current_user: CurrentUserDep):
return {"message": "Hello World"}
instead of:
# DO NOT DO THIS
@app.get("/items/")
async def read_item(current_user: dict = Depends(get_current_user)):
return {"message": "Hello World"}
Do not use Ellipsis for path operations or Pydantic models
Do not use ... as a default value for required parameters, it's not needed and not recommended.
Do this, without Ellipsis (...):
from typing import Annotated
from fastapi import FastAPI, Query
from pydantic import BaseModel, Field
class Item(BaseModel):
name: str
description: str | None = None
price: float = Field(gt=0)
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item, project_id: Annotated[int, Query()]): ...
instead of this:
# DO NOT DO THIS
class Item(BaseModel):
name: str = ...
description: str | None = None
price: float = Field(..., gt=0)
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item, project_id: Annotated[int, Query(...)]): ...
Return Type or Response Model
When possible, include a return type. It will be used to validate, filter, document, and serialize the response.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
@app.get("/items/me")
async def get_item() -> Item:
return Item(name="Plumbus", description="All-purpose home device")
Important: Return types or response models are what filter data ensuring no sensitive information is exposed. And they are used to serialize data with Pydantic (in Rust), this is the main idea that can increase response performance.
The return type doesn't have to be a Pydantic model, it could be a different type, like a list of integers, or a dict, etc.
When to use response_model instead
If the return type is not the same as the type that you want to use to validate, filter, or serialize, use the response_model parameter on the decorator instead.
from typing import Any
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
@app.get("/items/me", response_model=Item)
async def get_item() -> Any:
return {"name": "Foo", "description": "A very nice Item"}
This can be particularly useful when filtering data to expose only the public fields and avoid exposing sensitive information.
from typing import Any
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class InternalItem(BaseModel):
name: str
description: str | None = None
secret_key: str
class Item(BaseModel):
name: str
description: str | None = None
@app.get("/items/me", response_model=Item)
async def get_item() -> Any:
item = InternalItem(
name="Foo", description="A very nice Item", secret_key="supersecret"
)
return item
Performance
Do not use ORJSONResponse or UJSONResponse, they are deprecated.
Instead, declare a return type or response model. Pydantic will handle the data serialization on the Rust side.
Including Routers
When declaring routers, prefer to add router level parameters like prefix, tags, etc. to the router itself, instead of in include_router().
Do this:
from fastapi import APIRouter, FastAPI
app = FastAPI()
router = APIRouter(prefix="/items", tags=["items"])
@router.get("/")
async def list_items():
return []
# In main.py
app.include_router(router)
instead of this:
# DO NOT DO THIS
from fastapi import APIRouter, FastAPI
app = FastAPI()
router = APIRouter()
@router.get("/")
async def list_items():
return []
# In main.py
app.include_router(router, prefix="/items", tags=["items"])
There could be exceptions, but try to follow this convention.
Apply shared dependencies at the router level via dependencies=[Depends(...)].
Dependency Injection
See the dependency injection reference for detailed patterns including yield with scope, and class dependencies.
Use dependencies when the logic can't be declared in Pydantic validation, depends on external resources, needs cleanup (with yield), or is shared across endpoints.
Apply shared dependencies at the router level via dependencies=[Depends(...)].
Async vs Sync path operations
Use async path operations only when fully certain that the logic called inside is compatible with async and await (it's called with await) or that doesn't block.
from fastapi import FastAPI
app = FastAPI()
# Use async def when calling async code
@app.get("/async-items/")
async def read_async_items():
data = await some_async_library.fetch_items()
return data
# Use plain def when calling blocking/sync code or when in doubt
@app.get("/items/")
def read_items():
data = some_blocking_library.fetch_items()
return data
In case of doubt, or by default, use regular def functions, those will be run in a threadpool so they don't block the event loop.
The same rules apply to dependencies.
Make sure blocking code is not run inside of async functions. The logic will work, but will damage the performance heavily.
When needing to mix blocking and async code, see Asyncer in the other tools reference.
Streaming (JSON Lines, SSE, bytes)
See the streaming reference for JSON Lines, Server-Sent Events (EventSourceResponse, ServerSentEvent), and byte streaming (StreamingResponse) patterns.
Tooling
See the other tools reference for details on uv, Ruff, ty for package management, linting, type checking, formatting, etc.
Other Libraries
See the other tools reference for details on other libraries:
- Asyncer for handling async and await, concurrency, mixing async and blocking code, prefer it over AnyIO or asyncio.
- SQLModel for working with SQL databases, prefer it over SQLAlchemy.
- HTTPX for interacting with HTTP (other APIs), prefer it over Requests.
Do not use Pydantic RootModels
Do not use Pydantic RootModel, instead use regular type annotations with Annotated and Pydantic validation utilities.
For example, for a list with validations you could do:
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import Field
app = FastAPI()
@app.post("/items/")
async def create_items(items: Annotated[list[int], Field(min_length=1), Body()]):
return items
instead of:
# DO NOT DO THIS
from typing import Annotated
from fastapi import FastAPI
from pydantic import Field, RootModel
app = FastAPI()
class ItemList(RootModel[Annotated[list[int], Field(min_length=1)]]):
pass
@app.post("/items/")
async def create_items(items: ItemList):
return items
FastAPI supports these type annotations and will create a Pydantic TypeAdapter for them, so that types can work as normally and there's no need for the custom logic and types in RootModels.
Use one HTTP operation per function
Don't mix HTTP operations in a single function, having one function per HTTP operation helps separate concerns and organize the code.
Do this:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
@app.get("/items/")
async def list_items():
return []
@app.post("/items/")
async def create_item(item: Item):
return item
instead of this:
# DO NOT DO THIS
from fastapi import FastAPI, Request
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
@app.api_route("/items/", methods=["GET", "POST"])
async def handle_items(request: Request):
if request.method == "GET":
return []
先判断是否适合
作者设计意图
作者的方法与取舍
边界和复核