01FastAPI基础入门

来源:黑马程序员PythonWeb开发:FastAPI从入门到实战视频教程,涵盖路由、依赖注入、Pydantic、异步编程、ORM、项目拆分、模型训练、部署、接口测试2025-12-10 09:00:00

本文开始日期:2026-10-15 15:03


1.基础语法

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

  • 异步性能高
  • 开发效率高
  • 自动生成文档

快速入门:

python 复制代码
from fastapi import FastAPI

# 创建一个fastapi实例
app = FastAPI()


# async代表异步,被async修饰的函数,是异步函数,可以处理并发请求。
@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

1.1路由

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

1.2参数

参数就是客户端发送请求时 附带的额外信息和指令

参数的作用是让同一个接口能根据不同的输入,返回不同的输出,实现动态交互

1.2.1路径参数

python 复制代码
@app.get("/book/{id}")
async def get_book(id: int):
    return {"id": id, "title": f"得到第{id}章"}

注意类型注解影响返回值:

  • 如果是int,返回{"id" : 666, "title" : "得到第666章"};如果是str,返回{"id" : "666", "title" : "得到第666章"};
  • 上面的类型注解是python原生注解,接下来看看Path注解

对于路径参数的例子,思考:如果要限制id在1-100,该怎么做?

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

python 复制代码
from fastapi import FastAPI,Path

# 使用Path参数限制id的范围在1-100
@app.get("/book/{id}")
async def get_book(id: int = Path(..., gt=0, lt=101, description="书籍id限制在1到100之间")):
    return {"id": id, "title": f"得到第{id}章"}


# 使用Path参数限制name的长度在2-10
@app.get("/author/{name}")
async def get_name(name: str = Path(..., min_length=2, max_length=10)):
    return {"msg":  f"这是{name}的信息"}

1.2.2查询参数

python 复制代码
@app.get("/news/news_list")
async def get_news_list(skip: int, limit: int = 10):
    return {"skip": skip, "limit": limit, "msg": "获取新闻列表成功"}

同样,如果需要对查询参数做限制,可以使用原生注解,也可以使用Query注解:

python 复制代码
from fastapi import FastAPI, Query

# 使用Query注解:skip参数默认值为0,需要小于100;limit参数默认值为10
@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, "msg": "获取新闻列表成功"}

1.2.3请求体参数

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

# 创建一个fastapi实例
app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}



class User(BaseModel):
    username: str
    password: str

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

同样,如果需要对请求体参数做限制,可以使用原生注解,也可以使用Field注解:

python 复制代码
from pydantic import BaseModel,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, description="密码,长度3-20个字")


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

1.3响应类型

1.3.1-JSON格式

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

响应类型设置方式:

1.3.2-HTML格式

python 复制代码
from fastapi.responses import HTMLResponse


@app.get("/html", response_class=HTMLResponse)
async def html_res():
    return "<h1>html响应格式</h1>"

1.3.3文件格式

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

python 复制代码
from fastapi.responses import FileResponse

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

1.3.4自定义响应数据格式

1.3.5异常响应处理

相关推荐
听风吹等浪起1 小时前
第25章:基于ConvNeXt实现肺部CT肺癌四分类:数据集、训练调优、网络结构与Streamlit网页部署
人工智能·分类·数据挖掘
艺杯羹1 小时前
Android无障碍自动化死循环全解:从动态角标伪匹配到单向状态机防御实战
人工智能·自动化·大语言模型
会编程的吕洞宾1 小时前
Spring AI 语义缓存:重复提问不重复花钱
java·人工智能·后端·spring
物联网老王1 小时前
第05篇-Agent 连不上工具?MCP 就是那根“USB-C”
开发语言·人工智能·ai·aigc·ai编程
镭封1 小时前
手机文字转语音怎么操作?新手从输入文案到导出音频
人工智能·智能手机·音视频·语音识别·媒体
samforce1 小时前
我拆了 399 个 AI 生成的网页:75% 拿 emoji 当图标,89% 用了大圆角,56% 是同一套四件套
人工智能
我喜欢就喜欢1 小时前
百度 AI 搜索实战应用场景与落地指南
人工智能·百度
像污秽一样1 小时前
动手学kaggle-Intro to Machine Learning-1
人工智能·机器学习