FastAPI:(2)开启FastAPI

发布于:2025-06-17 ⋅ 阅读:(12) ⋅ 点赞:(0)

FastAPI:(2)开启FastAPI

由于CSDN无法展示「渐构」的「#d,#e,#t,#c,#v,#a」标签,推荐访问我个人网站进行阅读:Hkini
「渐构展示」如下:在这里插入图片描述
在这里插入图片描述
#e FastAPI例子

from fastapi import FastAPI # 导入FastAPI

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

@app.get("/") # 创建一个路径操作,「路径」也通常被称为「端点」或「路由」。
async def root(): # 定义路径操作函数。每当FastAPI接收一个使用GET方法访问 URL「/」的请求时这个函数会被调用。
    return {"message": "Hello World"}

运行服务:

fastapi dev main.py

   FastAPI   Starting development server 🚀

             Searching for package file structure from directories
             with __init__.py files
             Importing from /home/user/code/awesomeapp

    module   🐍 main.py

      code   Importing the FastAPI app object from the module with
             the following code:

             from main import app

       app   Using import string: main:app

    server   Server started at http://127.0.0.1:8000
    server   Documentation at http://127.0.0.1:8000/docs

       tip   Running in development mode, for production use:
             fastapi run

             Logs:

      INFO   Will watch for changes in these directories:
             ['/home/user/code/awesomeapp']
      INFO   Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C
             to quit)
      INFO   Started reloader process [383138] using WatchFiles
      INFO   Started server process [383153]
      INFO   Waiting for application startup.
      INFO   Application startup complete.

#d OpenAPI

OpenAPI 是一种用于定义 RESTful API 的规范(以前称为 Swagger 规范),它使用标准的、与语言无关的格式(通常是 JSON 或 YAML)来描述 API 的路径、参数、响应、请求体等内容。在 FastAPI 中,OpenAPI 被自动集成,用于自动生成 API 文档(如 Swagger UI、ReDoc),并使得客户端代码生成、接口验证等功能成为可能。FastAPI 使用定义 API 的 OpenAPI 标准将所有 API 转换成「模式」。

重要特征

  • 自动化描述能力
    OpenAPI 能够自动地将代码中的接口定义转换成结构化文档,无需手动维护文档。

  • 可视化文档生成
    FastAPI 使用 OpenAPI 自动生成 Swagger UI,使得 API 结构、参数、响应一目了然。

  • 语言无关性与互操作性强
    OpenAPI 使用标准格式(JSON/YAML),可以被多种语言和工具链识别和使用(如 Postman、代码生成器等)。

  • 支持验证与交互
    OpenAPI 文档可以支持输入参数和输出结果的格式验证,并通过 Swagger UI 进行接口测试。

#e 医疗系统API(正例) OpenAPI

现象
一个医疗管理系统使用 FastAPI 构建,所有接口(如病人信息查询、预约管理、处方提交)都通过 pydantic 明确定义了请求体和响应模型,并使用 FastAPI 自动生成的 Swagger UI 提供交互式文档,供前端和测试团队使用。

特征对比

特征 表现情况
自动化描述能力 FastAPI 自动生成 OpenAPI 文档
可视化文档生成 提供 Swagger UI 和 ReDoc
语言无关与互操作性 OpenAPI 文档可导入 Postman 使用
验证与交互支持 Swagger UI 可直接测试参数与结果格式

#e Flask接口文档(反例) OpenAPI

现象
某传统项目使用 Flask 编写 RESTful API,但所有接口文档靠 Markdown 手写维护。接口参数、响应字段、状态码等均靠开发者手动同步,无法通过代码生成或工具交互测试。

特征对比

特征 表现情况
自动化描述能力 ❌ 无自动文档,文档与代码容易不一致
可视化文档生成 ❌ 只能阅读手动文档,无法交互
语言无关与互操作性 ❌ 文档格式无法用于自动生成客户端代码
验证与交互支持 ❌ 无法通过 UI 验证接口功能

#d 模式

在 FastAPI 及 OpenAPI 中,「模式」是对数据或结构的抽象描述,而非实现代码。它定义了接口(API)的结构、请求与响应的数据格式、字段类型、是否必填、默认值等。OpenAPI 规范使用 JSON Schema 标准来描述这些 API 和数据的「模式」。换句话说,「模式」是对 API 接口行为与数据结构的统一描述标准,用于自动生成文档、验证输入、支持交互等功能。

重要特征:

  • 抽象性
    模式是对数据和接口的定义,并不涉及实际的逻辑实现。

  • 结构性
    模式中清晰地规定了路径、请求参数、响应内容、字段类型等结构。

  • 一致性与可验证性
    使用 JSON Schema 描述的模式可被用来验证输入数据是否满足要求。

  • 生成性
    模式可被用于自动生成文档、测试界面,甚至客户端 SDK。

  • 语义明确性
    模式使用标准格式(如 OpenAPI + JSON Schema),具备良好的互操作性和规范性。

#e 数据模式 模式

User 是一个数据模式。它通过 pydantic 转换为 OpenAPI JSON Schema,供前后端验证结构。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str
    email: str

@app.post("/users/")
def create_user(user: User):
    return {"message": "user received", "data": user}

#e API模式 模式

路径、方法、参数、响应结构等都自动被 FastAPI 转换为 OpenAPI 模式,可在 /docs 中看到。

@app.get("/predict", tags=["AI"])
def predict(age: int, weight: float):
    return {"risk": "high" if age > 50 else "low"}

#e 数据库模式 模式

使用 SQLModelSQLAlchemy,定义数据库模式:

from sqlmodel import SQLModel, Field

class Product(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    price: float

#e UI模式 模式

同时 FastAPI 提供接口响应:

@app.get("/form-schema")
def get_form_schema():
    return {
        "type": "object",
        "properties": {
            "username": {"type": "string", "title": "用户名"},
            "age": {"type": "number", "title": "年龄"}
        },
        "required": ["username"]
    }

网站公告

今日签到

点亮在社区的每一天
去签到