· 约 2 分钟

03-FastAPI基础入门-第一个FastAPI程序

  • FastAPI
  • Python

学习目标

核心概念

第一个 FastAPI 程序的目标不是“把功能写复杂”,而是先跑通最小闭环:

  1. 安装依赖
  2. 写出 app = FastAPI()
  3. 定义一个路由
  4. uvicorn 启动
  5. 打开 /docs

常用安装命令:

pip install fastapi uvicorn

启动命令:

uvicorn main:app --reload

其中:

代码示例

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"message": "Hello FastAPI"}


@app.get("/ping")
def ping():
    return {"status": "ok"}

运行结果

启动后通常访问:

其中 /docs 是学习 FastAPI 时非常重要的页面,因为它不仅能看接口说明,还能直接在线测试。

易错点

我的补充

第一次学 FastAPI,一定要把 /docs 养成习惯。后面很多参数校验和请求体结构,看文档页比只看代码更直观。