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
相关推荐
摇滚侠4 小时前
Java 零基础全套教程,集合框架,笔记 153-163
java·开发语言·笔记
ゆづき5 小时前
计算机数据存储全解:从底层进制转换到存储介质演进
笔记·学习·生活
小+不通文墨5 小时前
树莓派玩转EMQX的常用指令清单
经验分享·笔记·学习
kdxiaojie6 小时前
U-Boot分析【学习笔记】(12)
linux·笔记·学习
玄米乌龙茶1237 小时前
LLM成长笔记(五):提示词工程与模型调用
人工智能·笔记
不会编程的懒洋洋7 小时前
VisionPro 中 几何相交工具 Geometry-Intersection
图像处理·笔记·c#·视觉检测·机器视觉·visionpro
_李小白7 小时前
【C++学习笔记】新特性之inline变量
c++·笔记·学习
心中有国也有家7 小时前
hccl 架构拆解:昇腾集合通信库到底在做什么?
人工智能·经验分享·笔记·分布式·算法·架构
~黄夫人~7 小时前
零基础速通|Windows&Linux 常用命令行对照表大全
linux·运维·windows·笔记·备忘录·整理表格
毋语天8 小时前
FastAPI 进阶实战:请求体、文件上传、响应模型与数据校验
python·fastapi·api开发·数据校验·pydantic