快速掌握FastAPI:高效构建Web API

FastAPI 简介

  • FastAPI 是一个基于 Python 的高性能 Web 框架,专门用于快速构建 API 接口服务

FastAPI 框架基础

使用 FastAPI 框架搭建 Web 服务

1. 创建项目

2. 运行项目

run运行


uvicorn main:app --reload 终端运行
--reload:更改代码后自动重启服务器

3. 访问项目


访问 FastAPI 交互式文档:

路由

路由: URL 地址和处理函数之间的映射关系,它决定了当用户访问某个特定网址时,服务器应该执行哪段代码来返回结果
示例:

python 复制代码
@app.get("/")
async def root():
    return {"message": "Hello World666"}


@app.post("/add_book")
async def add_book(book: Book):
    return book

参数

同一段接口逻辑,根据参数不同返回不同的数据


参数就是客户端发送请求时附带的额外信息和指令
参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互

路径参数

URL 路径设置参数
python 复制代码
@app.get("/user/{id}")
async def get_user(id: int):
    return {"id": id, "titleName": f"这是用户{id}"}
路径参数 - 类型注解 Path

FastAPI 允许为参数声明额外的信息和校验

|-----------------------|---------|
| Path 参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

python 复制代码
from fastapi import FastAPI, Path

@app.get("/newsClassificationId/{id}")
async def get_news_classification_id(id: int = Path(..., ge=1, le=100, description="新闻分类id")):
    return {"id": id, "titleName": f"新闻分类id为{id}"}

查询参数

声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数

python 复制代码
@app.get("/news/news_list")
async def get_news_list(skip: int, limit: int=10):
return {"skip": skip, "limit": limit}
查询参数 - 类型注解 Query

|-----------------------|---------|
| Query参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

python 复制代码
from fastapi import FastAPI, Path, Query

@app.get("/book/query_list")
async def get_query_book_list(
        type: str = Query("Python开发", min_length=5, max_length=255, description="图书分类名称"),
        price: int = Query(..., ge=50, le=100, description="图书价格"), ):
    return {"type": f"图书分类名称为{type}", "price": f"价格为{price}"}

请求体参数

HTTP 请求的消息体 (body)中
在HTTP协议中,一个完整的请求由三部分组成:
① 请求行:包含方法、URL、协议版本
② 请求头:元数据信息(Content-Type、Authorization等)
③ 请求体:实际要发送的数据内容

python 复制代码
from pydantic import BaseModel

class Book(BaseModel):
    bookTitle: str
    author: str
    publishingHouse: str
    price: int

@app.post("/add_book")
async def add_book(book: Book):
    return book
请求体参数 - 类型注解 Field

|-----------------------|---------|
| Field 参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

python 复制代码
以图书信息为请求体参数设计URL,要求响应结果包含图书名称、作者、出版社、价格,并且图书名称、作者、价格长度范围2-20、2-10、0-100内
# 新增图书
from pydantic import BaseModel,Field

class Book2(BaseModel):
    bookTitle: str = Field(..., min_length=2, max_length=20, description="书名")
    author: str = Field(min_length=2, max_length=10, description="作者")
    publishingHouse: str = Field(default="星空椰出版社", description="出版社")
    price: int = Field(..., gt=0, description="价格")


@app.post("/add_book2")
async def add_book(book: Book2):
    return book

请求与响应

响应类型

|-------------------|---------------|----------------------------------|
| 响应类型 | 用途 | 示例 |
| JSONResponse | 默认响应,返回JSON数据 | return {"key": "value"} |
| HTMLResponse | 返回HTML内容 | return HTMLResponse(content) |
| PlainTextResponse | 返回纯文本 | return PlainTextResponse("text") |
| FileResponse | 返回文件下载 | return FileResponse(path) |
| StreamingResponse | 流式响应 | 生成器函数返回数据 |
| RedirectResponse | 重定向 | return RedirectResponse(url) |

响应类型设置方式

装饰器中指定响应类
一般用于固定返回类型(HTML、纯文本等)

python 复制代码
from starlette.responses import HTMLResponse

@app.get("/html", response_class=HTMLResponse)
async def get_html():
    return "<h1>这是一级标题</h1>"

返回响应对象
用于文件下载、图片、流式响应

python 复制代码
from fastapi.responses import FileResponse

@app.get("/file")
async def get_file():
file_path = "./files/1.jpeg"
    return FileResponse(file_path)

自定义响应数据格式

response_model 是路径操作装饰器(如 @app.get或 @app.post)的关键参数,它通过一个 Pydantic 模型来严格定义和约束 API 端点的输出格式。

python 复制代码
from pydantic import BaseModel

class News(BaseModel):
    id: int
    title: str
    content: str

@app.get("/news/{id}", response_model=News)
async def get_news(id: int):
    return {
        "id": id,
        "title": f"这是第{id}本书",
        "content": "这是一本好书"
    }

异常处理

操作接口出现异常,应使用 fastapi.HTTPException 来中断正常处理流程, 并返回标准错误响应

python 复制代码
from fastapi import FastAPI, HTTPException
@app.get('/news/{id}')
async def get_news(id: int):
    id_list = [1, 2, 3, 4, 5, 6]
    if id not in id_list:
        raise HTTPException(status_code=404, detail="当前id不存在")
    return {"id": id}

相关推荐
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB2 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码2 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵3 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li3 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸3 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学3 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田4 天前
Pydantic校验配置文件
python
hboot4 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络