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
相关推荐
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
闲云一鹤3 天前
Python 入门(二)- 使用 FastAPI 快速生成后端 API 接口
python·fastapi
曲幽3 天前
FastAPI + Ollama 实战:搭一个能查天气的AI助手
python·ai·lora·torch·fastapi·web·model·ollama·weatherapi
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky4 天前
Django入门笔记
笔记·django
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain