FastAPI 入门笔记

开发环境:Pycharm、miniconda

接口交互式文档网址:http://localhost:8000/docs

网页主页网址:127.0.0.1:8000

运行项目命令:

bash 复制代码
uvicorn main:app --reload

一、入门

1.路由和参数

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

参数:客户端发送请求时附带的额外信息和指令;作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互;分为三类,路径参数、查询参数、请求体

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

app = FastAPI()

# 路径参数
# Path为参数声明额外的信息和校验
@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, le=100, description="书籍ID的取值范围在1到100之间")):

    return {"id": id, "message": f"这是第{id}本书"}


# 查询参数
# Query为参数声明额外的信息和校验
@app.get("/news/news_list")
async def get_news_list(
        skip: int = Query(0, description="跳过的记录数", lt=100),
        limit: int = Query(10, description="返回的记录数")
):
    return {"skip": skip, "limit": limit}


# 请求体参数
# Field为参数声明额外的信息和校验
class User(BaseModel):
    username: str = Field(default="张三", min_length=2, max_length=10, description="用户名长度要求2到10个字")
    password: str = Field(min_length=3, max_length=20)

@app.post("/register")
async def register(user: User):
    return user

2.响应类型

响应类型:默认为JSON,三种格式:装饰器中指定响应类、返回响应对象、自定义响应格式

python 复制代码
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, FileResponse
from pydantic import BaseModel

app = FastAPI()

# 装饰器中指定响应类
@app.get("/html", response_class=HTMLResponse)
async def get_html():
    return "<h1>Hello World</h1>"

# 返回响应对象
@app.get("/file")
async def get_file():
    file_path = "./files/1.jpeg"
    return FileResponse(file_path)

# 自定义响应格式
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": "这是一本好书"
    }

3.异常处理

异常处理:对于客户端引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程,并返回标准错误响应

python 复制代码
from fastapi import FastAPI, HTTPException

app = FastAPI()

@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="您查找的新闻不存在")

    return {"id": id}

二、进阶

1.中间件

中间件(Middleware)是一个在每次请求进入 FastAPI 应用时都会被执行的函数。它在请求到达实际的路径操作(路由处理函数)之前运行,并且在响应返回给客户端之前再运行一次。

python 复制代码
from fastapi import FastAPI

app = FastAPI()

#中间件 自下而上

@app.middleware("http")
async def middleware1(request, call_next):
    print("中间件1 开始")
    response = await call_next(request)
    print("中间件1 结束")
    return response

@app.middleware("http")
async def middleware2(request, call_next):
    print("中间件2 开始")
    response = await call_next(request)
    print("中间件2 结束")
    return response
python 复制代码
# 输出
中间件2 开始
中间件1 开始
中间件1 结束
中间件2 结束

2.依赖注入

使用依赖注入系统来共享通用逻辑,避免代码重复

依赖项:可重用的组件(函数/类),负责提供某种功能或数据。

注入:FastAPI 自动帮你调用依赖项,并将结果"注入"到路径操作函数中

python 复制代码
from fastapi import FastAPI, Query

app = FastAPI()


async def common_parameters(
        skip: int = Query(0, ge=0),
        limit: int = Query(10, le=30)
):
    return {"skip": skip, "limit": limit}

@app.get("/news/news_list")
async def get_news_list(commons = Depends(common_parameters)):
    return commons

@app.get("/user/user_list")
async def get_user_list(commons = Depends(common_parameters)):
    return commons
相关推荐
Hello_Embed2 小时前
libmodbus 移植 STM32(USB 串口后端篇)
笔记·stm32·单片机·嵌入式·freertos·libmodbus
张祥6422889042 小时前
RTKLIB源码和理论结合分析笔记三
笔记
日更嵌入式的打工仔2 小时前
0欧电阻作用
笔记
wdfk_prog3 小时前
[Linux]学习笔记系列 -- [drivers][I2C]I2C
linux·笔记·学习
觉醒大王3 小时前
哪些文章会被我拒稿?
论文阅读·笔记·深度学习·考研·自然语言处理·html·学习方法
方安乐4 小时前
科普:股票 vs 债券的区别
笔记
傻小胖6 小时前
22.ETH-智能合约-北大肖臻老师客堂笔记
笔记·区块链·智能合约
浅念-6 小时前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
张人玉7 小时前
VisionPro 定位与卡尺测量学习笔记
笔记·学习·计算机视觉·vsionprp
songyuc7 小时前
【BiFormer】BiFormer: Vision Transformer with Bi-Level Routing Attention 译读笔记
笔记·transformer