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
相关推荐
李帅朋2 小时前
微分基本定义笔记
人工智能·笔记·深度学习·神经网络
xian_wwq4 小时前
【学习笔记】深度认知系列-第16讲-提示词工程
人工智能·笔记·学习
youm20035 小时前
认识Redis
redis·笔记·学习
亮工硬件6 小时前
1-11 STM32内部FLASH(数据掉电保存)
笔记·stm32·单片机·嵌入式硬件·学习
青 春 记 忆7 小时前
零基础入门python66:FastAPI AI标题、摘要和标签
python·fastapi·后端开发
青 春 记 忆8 小时前
零基础入门python65:FastAPI 安全调用大模型API
python·fastapi·后端开发
逆风飞翔的小叔8 小时前
【Python 基础】FastAPI ORM 操作MySql 实战使用详解
fastapi·fastapi orm·fastapi orm详解·fastapi orm使用·fastapi orm操作
疯狂打码的少年9 小时前
【数据库技术】复习日:关系代数 + SQL + 规范化(整理对比表)
jvm·数据库·笔记·sql
维克兜率天9 小时前
【维克】特征归一化与标准化:为什么模型对数据的“尺度“很敏感?
人工智能·笔记·python·机器学习·量化
摇滚侠9 小时前
《SpringBoot 3:入门与应用实战》第 12 章 JDBC 与事务 使用 JdbcTemplate 阅读笔记 31
android·spring boot·笔记