文章
Python 首批细教程 · 04B:用 FastAPI 做一个带 Swagger 文档的 JSON API
阅读数据加载中…
点赞数据加载中…
对应原仓库:
Day56-60/56-60.用FastAPI开发数据接口.md已提供可运行示例:
/tutorial-assets/python-100-days/04b-fastapi-swagger/(站点源码路径:blog-src/static/tutorial-assets/python-100-days/04b-fastapi-swagger/)
FastAPI 最值钱的体验,不是“能起服务”,而是很快得到一个结构清晰、可调试、自动有文档的接口。
Step 1:安装
cd blog-src/static/tutorial-assets/python-100-days/04b-fastapi-swagger
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
Step 2:写接口
示例目录已经提供 main.py(站点源码路径:blog-src/static/tutorial-assets/python-100-days/04b-fastapi-swagger/main.py):
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class EchoBody(BaseModel):
name: str
age: int
@app.get("/")
def home():
return {"code": 200, "message": "hello, world!"}
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "name": f"user-{user_id}"}
@app.post("/echo")
def echo(body: EchoBody):
return {"received": body.model_dump()}
Step 3:启动
uvicorn main:app --reload
访问:
//users/5/docs
/docs 会直接给你 Swagger UI,这就是 FastAPI 特别适合接口开发的原因之一。
Step 4:用 curl 调一下 POST
curl -X POST http://127.0.0.1:8000/echo \
-H "Content-Type: application/json" \
-d '{"name":"zhao","age":18}'
你会得到:
{"received":{"name":"zhao","age":18}}
这一篇和原仓库怎么对上
原仓库里给了一个最小 hello world,这里我们往前推了一步:
- 路径参数;
- 请求体模型;
- 自动文档;
- 实际调试。
这几步走完,FastAPI 才真正开始“像接口框架”。
常见坑
uvicorn main:app --reload里模块名和变量名写错。- POST 不传 JSON 头。
- 路径参数声明成
int,结果访问/users/abc报校验错。