FastAPI 快速入门
一、安装
bash
pip install fastapi uvicorn
二、基础 GET 接口
新建 main.py:
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def hello(name: str = "world"):
return {"message": f"hello {name}"}
三、POST 接口实战
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
# 定义请求体模型,自动校验类型
class Item(BaseModel):
name: str
price: float
is_offer: bool = False # 可选字段,默认False
@app.post("/items/")
def create_item(item: Item):
final_price = item.price * 0.9 if item.is_offer else item.price
return {"name": item.name, "final_price": final_price}
请求自动映射流程
#mermaid-svg-ei30NSHcOwQrmH9a{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-ei30NSHcOwQrmH9a .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-ei30NSHcOwQrmH9a .error-icon{fill:#552222;}#mermaid-svg-ei30NSHcOwQrmH9a .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-ei30NSHcOwQrmH9a .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-ei30NSHcOwQrmH9a .marker{fill:#333333;stroke:#333333;}#mermaid-svg-ei30NSHcOwQrmH9a .marker.cross{stroke:#333333;}#mermaid-svg-ei30NSHcOwQrmH9a svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-ei30NSHcOwQrmH9a p{margin:0;}#mermaid-svg-ei30NSHcOwQrmH9a .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-ei30NSHcOwQrmH9a .cluster-label text{fill:#333;}#mermaid-svg-ei30NSHcOwQrmH9a .cluster-label span{color:#333;}#mermaid-svg-ei30NSHcOwQrmH9a .cluster-label span p{background-color:transparent;}#mermaid-svg-ei30NSHcOwQrmH9a .label text,#mermaid-svg-ei30NSHcOwQrmH9a span{fill:#333;color:#333;}#mermaid-svg-ei30NSHcOwQrmH9a .node rect,#mermaid-svg-ei30NSHcOwQrmH9a .node circle,#mermaid-svg-ei30NSHcOwQrmH9a .node ellipse,#mermaid-svg-ei30NSHcOwQrmH9a .node polygon,#mermaid-svg-ei30NSHcOwQrmH9a .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-ei30NSHcOwQrmH9a .rough-node .label text,#mermaid-svg-ei30NSHcOwQrmH9a .node .label text,#mermaid-svg-ei30NSHcOwQrmH9a .image-shape .label,#mermaid-svg-ei30NSHcOwQrmH9a .icon-shape .label{text-anchor:middle;}#mermaid-svg-ei30NSHcOwQrmH9a .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-ei30NSHcOwQrmH9a .rough-node .label,#mermaid-svg-ei30NSHcOwQrmH9a .node .label,#mermaid-svg-ei30NSHcOwQrmH9a .image-shape .label,#mermaid-svg-ei30NSHcOwQrmH9a .icon-shape .label{text-align:center;}#mermaid-svg-ei30NSHcOwQrmH9a .node.clickable{cursor:pointer;}#mermaid-svg-ei30NSHcOwQrmH9a .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-ei30NSHcOwQrmH9a .arrowheadPath{fill:#333333;}#mermaid-svg-ei30NSHcOwQrmH9a .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-ei30NSHcOwQrmH9a .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-ei30NSHcOwQrmH9a .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ei30NSHcOwQrmH9a .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-ei30NSHcOwQrmH9a .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ei30NSHcOwQrmH9a .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-ei30NSHcOwQrmH9a .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-ei30NSHcOwQrmH9a .cluster text{fill:#333;}#mermaid-svg-ei30NSHcOwQrmH9a .cluster span{color:#333;}#mermaid-svg-ei30NSHcOwQrmH9a div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-ei30NSHcOwQrmH9a .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-ei30NSHcOwQrmH9a rect.text{fill:none;stroke-width:0;}#mermaid-svg-ei30NSHcOwQrmH9a .icon-shape,#mermaid-svg-ei30NSHcOwQrmH9a .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-ei30NSHcOwQrmH9a .icon-shape p,#mermaid-svg-ei30NSHcOwQrmH9a .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-ei30NSHcOwQrmH9a .icon-shape .label rect,#mermaid-svg-ei30NSHcOwQrmH9a .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-ei30NSHcOwQrmH9a .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-ei30NSHcOwQrmH9a .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-ei30NSHcOwQrmH9a :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 发送请求
自动映射 + 类型校验
客户端 POST JSON
{name: '可乐', price: 5}
FastAPI 接收请求
Pydantic Item 实例
业务逻辑处理
自动序列化返回 JSON
客户端收到响应
核心特性:请求体自动映射与校验
这是 FastAPI + Pydantic 最核心的魔力:
- 只要 POST 请求的 JSON 字段名与
Item类字段名一一对应,就会自动映射 成Item实例,无需手动解析 JSON - 自动完成参数校验:缺必填字段、类型不匹配时,直接返回标准 422 错误,无需手写判断逻辑
- 自动类型转换:例如传字符串
"5"给price: float,会自动转为数字5.0 - 自动补全默认值:不传
is_offer时,自动填充默认值False 
四、启动与测试
启动服务
bash
uvicorn main:app --reload
两种测试方式
- 自动交互式文档 :浏览器打开
http://127.0.0.1:8000/docs,可视化调试接口 - 命令行调用
bash
# GET 测试
curl http://127.0.0.1:8000/?name=fastapi
# POST 测试
curl -X POST http://127.0.0.1:8000/items/ \
-H "Content-Type: application/json" \
-d '{"name":"可乐","price":5,"is_offer":true}'
五、为什么 FastAPI 这么火
- 性能强:基于 Starlette + Pydantic,是 Python 最快的 Web 框架之一,性能接近 Go/Node.js
- 效率高:靠类型注解自动完成参数校验、类型转换,零配置生成 OpenAPI 文档
- 标准兼容:原生支持 OpenAPI、JSON Schema 规范,适配前后端分离、微服务、AI 接口等场景
- 门槛低:语法贴近原生 Python,兼容现有 Python 生态,学习成本极低