快速掌握FastAPI:高效构建Web API

FastAPI 简介

  • FastAPI 是一个基于 Python 的高性能 Web 框架,专门用于快速构建 API 接口服务

FastAPI 框架基础

使用 FastAPI 框架搭建 Web 服务

1. 创建项目

2. 运行项目

run运行


uvicorn main:app --reload 终端运行
--reload:更改代码后自动重启服务器

3. 访问项目


访问 FastAPI 交互式文档:

路由

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

python 复制代码
@app.get("/")
async def root():
    return {"message": "Hello World666"}


@app.post("/add_book")
async def add_book(book: Book):
    return book

参数

同一段接口逻辑,根据参数不同返回不同的数据


参数就是客户端发送请求时附带的额外信息和指令
参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互

路径参数

URL 路径设置参数
python 复制代码
@app.get("/user/{id}")
async def get_user(id: int):
    return {"id": id, "titleName": f"这是用户{id}"}
路径参数 - 类型注解 Path

FastAPI 允许为参数声明额外的信息和校验

|-----------------------|---------|
| Path 参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

python 复制代码
from fastapi import FastAPI, Path

@app.get("/newsClassificationId/{id}")
async def get_news_classification_id(id: int = Path(..., ge=1, le=100, description="新闻分类id")):
    return {"id": id, "titleName": f"新闻分类id为{id}"}

查询参数

声明的参数不是路径参数时,路径操作函数会把该参数自动解释为查询参数

python 复制代码
@app.get("/news/news_list")
async def get_news_list(skip: int, limit: int=10):
return {"skip": skip, "limit": limit}
查询参数 - 类型注解 Query

|-----------------------|---------|
| Query参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

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

@app.get("/book/query_list")
async def get_query_book_list(
        type: str = Query("Python开发", min_length=5, max_length=255, description="图书分类名称"),
        price: int = Query(..., ge=50, le=100, description="图书价格"), ):
    return {"type": f"图书分类名称为{type}", "price": f"价格为{price}"}

请求体参数

HTTP 请求的消息体 (body)中
在HTTP协议中,一个完整的请求由三部分组成:
① 请求行:包含方法、URL、协议版本
② 请求头:元数据信息(Content-Type、Authorization等)
③ 请求体:实际要发送的数据内容

python 复制代码
from pydantic import BaseModel

class Book(BaseModel):
    bookTitle: str
    author: str
    publishingHouse: str
    price: int

@app.post("/add_book")
async def add_book(book: Book):
    return book
请求体参数 - 类型注解 Field

|-----------------------|---------|
| Field 参数 | 说明 |
| ... | 必填 |
| gt/ge | 大于/大于等于 |
| lt/le | 小于/小于等于 |
| description | 描述 |
| min_length max_length | 长度限制 |
| min_length max_length | 长度限制 |

python 复制代码
以图书信息为请求体参数设计URL,要求响应结果包含图书名称、作者、出版社、价格,并且图书名称、作者、价格长度范围2-20、2-10、0-100内
# 新增图书
from pydantic import BaseModel,Field

class Book2(BaseModel):
    bookTitle: str = Field(..., min_length=2, max_length=20, description="书名")
    author: str = Field(min_length=2, max_length=10, description="作者")
    publishingHouse: str = Field(default="星空椰出版社", description="出版社")
    price: int = Field(..., gt=0, description="价格")


@app.post("/add_book2")
async def add_book(book: Book2):
    return book

请求与响应

响应类型

|-------------------|---------------|----------------------------------|
| 响应类型 | 用途 | 示例 |
| JSONResponse | 默认响应,返回JSON数据 | return {"key": "value"} |
| HTMLResponse | 返回HTML内容 | return HTMLResponse(content) |
| PlainTextResponse | 返回纯文本 | return PlainTextResponse("text") |
| FileResponse | 返回文件下载 | return FileResponse(path) |
| StreamingResponse | 流式响应 | 生成器函数返回数据 |
| RedirectResponse | 重定向 | return RedirectResponse(url) |

响应类型设置方式

装饰器中指定响应类
一般用于固定返回类型(HTML、纯文本等)

python 复制代码
from starlette.responses import HTMLResponse

@app.get("/html", response_class=HTMLResponse)
async def get_html():
    return "<h1>这是一级标题</h1>"

返回响应对象
用于文件下载、图片、流式响应

python 复制代码
from fastapi.responses import FileResponse

@app.get("/file")
async def get_file():
file_path = "./files/1.jpeg"
    return FileResponse(file_path)

自定义响应数据格式

response_model 是路径操作装饰器(如 @app.get或 @app.post)的关键参数,它通过一个 Pydantic 模型来严格定义和约束 API 端点的输出格式。

python 复制代码
from pydantic import BaseModel

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": "这是一本好书"
    }

异常处理

操作接口出现异常,应使用 fastapi.HTTPException 来中断正常处理流程, 并返回标准错误响应

python 复制代码
from fastapi import FastAPI, HTTPException
@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="当前id不存在")
    return {"id": id}

相关推荐
0思必得07 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
沈浩(种子思维作者)7 小时前
系统要活起来就必须开放包容去中心化
人工智能·python·flask·量子计算
2301_790300967 小时前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
m0_736919107 小时前
用Pandas处理时间序列数据(Time Series)
jvm·数据库·python
getapi7 小时前
实时音视频传输与屏幕共享(投屏)
python
java干货8 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法
机器懒得学习8 小时前
智能股票分析系统
python·深度学习·金融
毕设源码-郭学长8 小时前
【开题答辩全过程】以 基于python的二手房数据分析与可视化为例,包含答辩的问题和答案
开发语言·python·数据分析
SR_shuiyunjian8 小时前
Python第三次作业
python
vx_biyesheji00018 小时前
豆瓣电影推荐系统 | Python Django 协同过滤 Echarts可视化 深度学习 大数据 毕业设计源码
大数据·爬虫·python·深度学习·django·毕业设计·echarts