FastAPI 项目设置与第一个端点
安装 FastAPI、创建项目,并编写您的第一个 GET 端点。
FastAPI 项目设置与第一个端点 是 CoddyKit 上的免费 Python Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Python Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Python Academy 课程共包含 4 节课。
什么是 FastAPI?
FastAPI 是用于构建 REST 接口的现代 Python Web 框架。它提供自动生成的 OpenAPI 文档、通过 Pydantic 进行类型检查的请求/响应模型,以及原生异步性能。
# pip install fastapi uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, FastAPI"}运行服务器
使用 uvicorn 运行。开发期间,代码发生更改时,--reload 标志会自动重启服务器。
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health(): return {"status": "ok"}
# Terminal:
# uvicorn main:app --reload
# → http://127.0.0.1:8000
# → http://127.0.0.1:8000/docs (Swagger UI)HTTP 方法
使用 @app.get、@app.post、@app.put、@app.delete 或 @app.patch 装饰路由函数。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def list_items(): return []
@app.post("/items")
def create_item(): return {"id": 1}
@app.delete("/items/{item_id}")
def delete_item(item_id: int): return {"deleted": item_id}路径参数
在路由字符串中使用 {name} 声明路径参数,并在函数参数中通过类型注解声明它们。
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "name": "Alice"}
# GET /users/42 → {"user_id": 42, "name": "Alice"}查询参数
不在路径中的函数参数会成为查询参数。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def list_items(skip: int = 0, limit: int = 10, q: str | None = None):
return {"skip": skip, "limit": limit, "q": q}
# GET /items?skip=5&limit=20&q=searchPydantic 请求体
将 Pydantic BaseModel 用作参数类型,即可声明并验证 JSON 请求体。
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
in_stock: bool = True
@app.post("/items")
def create_item(item: Item):
return {"received": item.model_dump()}Pydantic 验证错误
如果请求体不符合架构,FastAPI 会自动返回 422 不可处理实体响应,并附带详细的错误消息。
# POST /items with body {"name": 123}
# → HTTP 422 Unprocessable Entity
# {
# "detail": [
# {
# "type": "string_type",
# "loc": ["body","name"],
# "msg": "Input should be a valid string"
# }
# ]
# }响应模型
使用 response_model= 声明端点返回的内容。FastAPI 会验证响应,并过滤掉多余字段。
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserOut(BaseModel):
id: int
name: str
@app.get("/users/{uid}", response_model=UserOut)
def get_user(uid: int):
return {"id": uid, "name": "Alice", "password": "secret"} # password filtered out状态码
使用 status_code= 设置默认的成功状态码。通过 fastapi.status 导入常用状态码。
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item():
return {"id": 1}
# HTTP 201 Created is returned on successHTTPException
引发 HTTPException,即可使用自定义状态码和详细消息返回错误响应。
from fastapi import FastAPI, HTTPException
app = FastAPI()
fake_db = {1: "Alice"}
@app.get("/users/{uid}")
def get_user(uid: int):
if uid not in fake_db:
raise HTTPException(status_code=404, detail="User not found")
return {"name": fake_db[uid]}自动生成文档
FastAPI 会根据路由注解自动在 /docs 生成 Swagger UI,并在 /redoc 生成 ReDoc。
# After starting with uvicorn:
# http://localhost:8000/docs — Swagger UI (try the API live)
# http://localhost:8000/redoc — ReDoc (clean docs view)
# http://localhost:8000/openapi.json — raw OpenAPI schema快速检查
如何在 FastAPI 中声明必需的 JSON 请求体参数?
回顾
FastAPI 路由是经过装饰的函数:路径参数位于 URL 中,查询参数是带类型的参数,请求体使用 Pydantic 模型。对于错误,请引发 HTTPException。Swagger UI 会自动在 /docs 生成。
常见问题解答
「FastAPI 项目设置与第一个端点」课时是免费的吗?
是的 — 「FastAPI 项目设置与第一个端点」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Python Academy 课程的其余内容,请升级到 CoddyKit PRO。 Python Academy 课程共包含 4 节课。
「FastAPI 项目设置与第一个端点」这节课中我会学到什么?
安装 FastAPI、创建项目,并编写您的第一个 GET 端点。 你通过在浏览器中直接运行的动手代码来练习 Python Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Python Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Python Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「FastAPI 项目设置与第一个端点」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Python Academy 课中编写并运行代码吗?
能。每节 Python Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- FastAPI 项目设置与第一个端点
- 路径参数、查询参数与请求体
- 依赖注入与身份验证
- 异步端点与数据库集成