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
相关推荐
hkNaruto15 小时前
【AI】AI学习笔记:A2A(智能体协作)入门指南:从概念到实践
人工智能·笔记·学习
yj_sharing15 小时前
动手学深度学习softmax回归的笔记
笔记·深度学习·回归
暖暖木头15 小时前
playwright学习笔记
笔记·学习
hetao173383715 小时前
2026-01-06 hetao1733837 的刷题笔记
c++·笔记·算法
qq_3975623116 小时前
昆仑通态屏幕 , 脚本使用笔记
笔记
koo36417 小时前
pytorch深度学习笔记12
pytorch·笔记·深度学习
慕容雪_18 小时前
运维笔记-网络共享
运维·笔记·网络共享
浩瀚地学19 小时前
【Java】异常
java·开发语言·经验分享·笔记·学习
一尘之中19 小时前
Ubuntu 22.04 上 FastAPI 的完整安装与问题解决指南
ubuntu·fastapi·ai写作