前言

同步和异步

同步(可能需要花费10s+):

@app.get("/sync")
def func_sync():
    start = time.time()
    for i in range(10):
        time.sleep(1)
    end = time.time()
    return {"time":f'{end-start:.2f}s'}

异步(1秒):

@app.get("/async")
def func_async():
    start = time.time()
    task = [asyncio.sleep(1) for i in range(10)]
    await asyncio.gather(*tasks)
    end = time.time()
    return {"time":f'{end-start:.2f}s'}

使用 FastAPI 框架搭建 Web 服务

第一个 FastAPI 程序

1.创建项目

FastAPI → 存储位置及项目名称 → 创建虚拟环境 → Create

2.运行项目

方法一:点击右上角的绿色三角就可以运行啦

方法二:

先点击左侧的terminal进入到命令行里

方法二:输入uvicorn main:app --reload命令启动命令

3. 访问项目

http://127.0.0.1:8000/  访问路由--前端请求数据的接口

http://127.0.0.1:8000/http://127.0.0.1:8000/docs  访问交互式文档http://127.0.0.1:8000/

路由

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

# 访问hello,响应结果--msg:hello fastapi
@app.get("/hello")
async def get_hello():
    return {"msg": "Hello fastAPI"}

练习

访问路径:/user/hello,响应结果:我正在学习,不要打扰我

@app.get("/user/hello")
async def get_hello_user():
    return {"msg": "我正在学习,不要打扰我"}

参数简介和路径参数

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

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

参数分类

路径参数

  • 位置:URL 路径的一部分 /card/{id}
  • 作用:指向唯一的、特定的 资源
  • 方法:GET
@app.get("/card/{id}")
async def get_card(id: int):
    return {"id": id,"title" : f"这是第{id}张卡"}

int 是参数类型注解

练习

以用户 id 为路径参数设计 URL,要求响应结果包含用户 id 和 名称(普通用户 id)

@app.get("/user/{id}")
async def get_user_id(id: int):
    return {"id":id,"name":f"普通用户{id}"}
path参数注解

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

导入 FastAPI 的 Path 函数

Path 参数 说明
... 必填
gt/ge lt/le(是int的限制 大于/大于等于 小于/小于等于
description 描述
min_length max_length(是str的限制 长度限制
from fastapi import FastAPI,Path
@app.get("/card/{id}")
async def get_card(id: int=Path(...,ge=1,le=100,description="卡id,取值范围1~100")):
    return {"id": id,"title" : f"这是第{id}张卡"}

如果输入不在该范围的数字,就会出现

"msg":"Input should be less than or equal to 100"
练习

接口:以用户名为参数设计URL,要求名称长度为2~6

@app.get("/user/{name}")
async def get_user_id(name: str=Path(...,min_length=2,max_length=6,description="用户名长度2~6")):
    return {"name":f"我的名字是{name}"}

查询参数

  • 位置:URL? 之后 k1=v1&k2=v2
  • 作用:对资源集合进行过滤、排序、分页等操作
  • 方法:GET

原生的:

# skip:跳过的记录数,limit:返回的记录数
@app.get("/user/user_list")
async def get_user_list(skip: int,limit: int=10):
    return {"skip":skip,"limit":limit}
http://127.0.0.1:8000/user/user_list?skip=0&limit=10
Query类型注解
@app.get("/user/user_list")
async def get_user_list(skip: int=Query(0,description="这是跳过的记录数"),
                        limit: int=Query(10,description="这是返回的记录数")):
    return {"skip":skip,"limit":limit}

请求体参数

  • 位置:HTTP 请求的消息体 (body)中
  • 作用:创建、更新资源 携带大量数据,如: JSON
  • 方法:POST、PUT 等

在HTTP协议中,一个完整的请求由三部分组成:

① 请求行​:包含方法、URL、协议版本

② 请求头​:元数据信息(Content-Type、Authorization等)

③ 请求体​:实际要发送的数据内容

from pydantic import BaseModel
class User(BaseModel):
    username: str
    password: str
    age:int
    grade:int

@app.post("/user")
async def create_user(user:User):
    return user

类型注解——Filed
Path 参数 说明
... 必填
gt/ge lt/le(是int的限制 大于/大于等于 小于/小于等于
default 默认值
description 描述
min_length max_length(是str的限制 长度限制
from fastapi import FastAPI
from pydantic import BaseModel,Field

# 创建实例
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}
# 注册用户名和密码 →str
class User(BaseModel):
    username: str=Field("王麻子",min_length=2,max_length=6)
    password: str=Field("<PASSWORD>",min_length=3)

@app.post("/user")
async def create_user(user:User):
    return user

响应类型

默认情况下,FastAPI 会自动将路径操作函数返回的 Python 对象(字典、列表、Pydantic 模型等),经由 jsonable_encoder 转换为 JSON 兼容格式,并包装为 JSONResponse 返回。这省去了手动序列化的步骤,让开发者能更专注于业务逻辑。 如果需要返回非 JSON 数据(如 HTML、文件流),FastAPI 提供了丰富的响应类型来返回不同数据

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

JSON 格式

默认情况下,FastAPI 会自动将路径操作函数返回的 Python 对象(字典、列表、Pydantic 模型等),经由 jsonable_encoder转换为 JSON 兼容格式,并包装为 JSONResponse 返回。

@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}

响应类型设置方式--装饰器中指定响应类

场景:固定返回类型(HTML、纯文本等)

HTML格式

设置响应类为 HTMLResponse,当前接口即可返回 HTML 内容

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

# 创建实例
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}

# 接口→响应HTML
@app.get("/html", response_class=HTMLResponse)
async def html():
    return HTMLResponse("<h1>这是一级标题html</h1>")

响应类型设置方式--返回响应对象

场景:文件下载、图片、流式响应

文件格式

FileResponse 是 FastAPI 提供的专门用于高效返回文件内容(如图片、PDF、Excel、音视频等)的响应类。它能够智能处理文件路径 、媒体类型推断、范围请求和缓存头部,是服务静态文件的推荐方式。

from fastapi import FastAPI
from fastapi.responses import FileResponse

# 创建实例
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}

# 接口→响应HTML
@app.get("/file")
async def file():
    path = "img.png"
    return FileResponse(path)

响应类型设置方式--自定义响应数据格式

response_model 是路径操作装饰器(如 @app.get或 @app.post)的关键参数,它通过一个 Pydantic模型来严格定义和约束 API 端点的输出格式。这一机制在提供自动数据验证和序列化的同时,更是保障数据安全性的第一道防线。

首先是正常模式:

from fastapi import FastAPI
from pydantic import BaseModel

# 创建实例
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}

# 用户接口 响应数据格式
class User(BaseModel):
    username : str
    age : int
    grade : str

@app.post("/user/{age}", response_model=User)
async def create_user(age:int):
    return {
        "username": f"这是{age}岁人的名字",
        "age": age,
        "grade": f"这是{age}岁人的年级"
    }

但是如果按照下面的写法就会:

@app.post("/user/{age}", response_model=User)
async def create_user(age:int):
    return {
        "username": f"这是{age}岁人的名字",
        "age": age
    }

缺少grade,就会出现下面的结果:

异常处理

对于客户端引发的错误(4xx,如资源未找到、认证失败),应使用 fastapi.HTTPException 来中断正常处理流程, 并返回标准错误响应 。

from fastapi import FastAPI,HTTPException

# 创建实例
app = FastAPI()


@app.get("/")
async def root():
    return {"message": "你好哈哈哈哈"}

# 用户接口 响应数据格式
@app.get("/user/{id}")
async def user(id:int):
    id_list = [1,2,3,6,9,10,4]
    if id not in id_list:
        raise HTTPException(status_code=404,detail="404 not found")
    return {"id":id}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐