快速掌握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}

相关推荐
塔尖尖儿2 小时前
Python中range()到底是什么演示
python
Ethan-D2 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
weixin_446934033 小时前
统计学中“in sample test”与“out of sample”有何区别?
人工智能·python·深度学习·机器学习·计算机视觉
weixin_462446234 小时前
使用 Python 测试 Mermaid 与 Graphviz 图表生成(支持中文)
python·mermaid·graphviz
JOBkiller1234 小时前
钢绞线缺陷检测与识别_Cascade-Mask-RCNN_RegNetX模型训练与应用实战
python
nvd114 小时前
深入 ReAct Agent 的灵魂拷问:从幻觉到精准执行的调试实录
python·langchain
Ulyanov4 小时前
战场地形生成与多源数据集成
开发语言·python·算法·tkinter·pyside·pyvista·gui开发
love530love4 小时前
告别环境崩溃:ONNX 与 Protobuf 版本兼容性指南
人工智能·windows·python·onnx·stablediffusion·comfyui·protobuf
ID_180079054735 小时前
日本乐天商品详情API接口的请求构造与参数说明
开发语言·python·pandas