跳转至

生成你的第一个 FastAPI 应用

在本页中,你将用 fastkit init 创建一个小型 FastAPI 应用,用 fastkit runserver 启动它,然后向它发送请求。在这个过程中,你会认识 FastAPI 的应用对象、路径操作、uvicorn 服务器,以及 FastAPI 自动为你生成的交互式 API 文档。

hello 级别会创建一个名为 shop 的项目,其中只有一个 main.py:包含三个端点和保存在内存中的条目。项目还为每个端点各附带一个测试。“学习”部分后面的页面都会沿用这个项目,所以请保留 shop 这个名称。你需要先安装 fastkit(安装),运行本页的命令还需要 uv。

创建项目

运行 fastkit init 的终端:项目名称 shop、“Levels”表格、“Project summary”和“Next steps”面板

在要存放项目的文件夹中运行 fastkit init。它会先询问项目名称,请输入 shop。接着它会列出五个级别的表格;之后的每个问题都直接按 Enter,保留默认值即可:选择 hello 级别,不做自定义,并确认创建项目。

$ fastkit init

⚡ Create a FastAPI project

Project name: shop
...

Select a level [1]:

Customise package manager and project details? [y/N]:

                                Project summary
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Setting         ┃ Value                                                      ┃
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Project name    │ shop                                                       │
│ Level           │ hello: One main.py: 3 endpoints, in-memory data, tests.    │
│ Template        │ fastapi-hello                                              │
│ Features        │ None added: the template's own code and tests              │
│ Author          │ (not set)                                                  │
│ Package manager │ uv                                                         │
│ Environment     │ .venv with dependencies installed                          │
└─────────────────┴────────────────────────────────────────────────────────────┘

Create the project? [Y/n]:
╭──────────────────────── Success ────────────────────────╮
│ ✨ Created 7 project files in the new folder 'shop'.    │
╰─────────────────────────────────────────────────────────╯
...
╭───────────────────────────────── Next steps ─────────────────────────────────╮
│ 1. Go to the project folder.                                                 │
│      cd shop                                                                 │
│ 2. Start the development server and open http://127.0.0.1:8000/docs.         │
│      fastkit runserver                                                       │
│ 3. Run the tests.                                                            │
│      uv run pytest                                                           │
│ 4. Add a resource by imitation: copy the `Item` models, `create_item`,       │
│    `read_item` and their tests, and rename them for `/users`.                │
│ 5. Read `main.py` from top to bottom: each comment links the FastAPI         │
│    tutorial page that explains it.                                           │
│ 6. When you want more structure, create a project at the next level.         │
│      fastkit init --level single-file                                        │
│ README.md lists the steps for a fresh checkout of the project.               │
╰──────────────────────────────────────────────────────────────────────────────╯

“Author”一行的值取自 git config(这里的 git 没有设置作者姓名)。fastkit 在 shop/.venv 中创建了虚拟环境,并把所需的包安装到其中。“Next steps”面板就是你接下来要做的事,项目的 README.md 则列出了在全新检出的项目中要执行的步骤。如果使用 fastkit init --no-venv,fastkit 只写入文件,之后在项目文件夹中运行 uv sync 即可创建 .venv,这和从 git 克隆项目之后的做法相同。

fastkit 创建了什么

shop/.gitignore
shop/README.md
shop/main.py
shop/pyproject.toml
shop/requirements-dev.txt
shop/requirements.txt
shop/tests/test_main.py
shop/uv.lock

main.py 就是整个应用,tests/test_main.py 负责测试它。pyproject.toml 列出项目所需的包;两个 requirements 文件为 pip 列出同样的包,uv.lock 则记录了 uv 实际安装的确切版本。

运行应用

$ fastkit runserver
...
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
...
INFO:     Application startup complete.

请在 shop 文件夹中运行这条命令(先执行 cd shop)。服务器会一直运行,直到你按下 Ctrl+C。每当你保存对 main.py 的修改,它还会自动重启。不使用 fastkit 时,uv run uvicorn main:app --reload 也能启动同样的服务器。

试一试

shop 应用 /docs 页面上的 Swagger UI:列出 GET /、POST /items 和 GET /items/{item_id},下方是“Schemas”部分

在浏览器中打开 http://127.0.0.1:8000/docs。这个页面列出了三个端点。点击其中一个,再依次点击“Try it out”和“Execute”,就能发送真实的请求并查看响应。http://127.0.0.1:8000/redoc 以参考文档的形式展示同一个 API。你也可以在第二个终端中发送请求:

$ curl -s http://127.0.0.1:8000/
{"message":"Hello, World! Welcome to shop","docs":"/docs"}
$ curl -s "http://127.0.0.1:8000/?name=Ada"
{"message":"Hello, Ada! Welcome to shop","docs":"/docs"}

刚才发生了什么

FastAPI 代码从应用对象开始,这个对象知道你的 API 中的每一个端点。带有 @app.get("/") 这类装饰器的函数称为路径操作:对于使用该 HTTP 方法(GET)、访问该路径(/)的请求,FastAPI 会调用这个函数,并把它的返回值转换成 JSON。

main.py
# `app` is the application object that uvicorn serves.
# https://fastapi.tiangolo.com/tutorial/first-steps/
app = FastAPI(title="shop")
# ...
@app.get("/")
async def read_root(
    # A str, int or bool argument not in the path is a query parameter: /?name=Ada
    # https://fastapi.tiangolo.com/tutorial/query-params/
    name: Annotated[str, Query(min_length=1, max_length=50)] = "World",
) -> dict[str, str]:
    return {"message": f"Hello, {name}! Welcome to {app.title}", "docs": "/docs"}

FastAPI 本身并不监听请求。负责这件事的服务器是 uvicorn:它接受 HTTP 连接,并通过 ASGI 把每个请求交给 app。ASGI 是 Python Web 服务器与应用之间的标准接口。fastkit runserver 会以 main:app 启动 uvicorn,意思是“main.py 中的 app 对象”。

FastAPI 会根据路径、类型提示和返回类型,为你的 API 编写一份 OpenAPI 描述。它是位于 /openapi.json 的 JSON 文档,列出每个端点及其参数和响应。/docs 和 /redoc 两个页面就是根据这份文档生成的。它们展示的是 FastAPI 能从代码中读到的内容,也就是你声明的路径、参数、模型和状态码。如果某个响应只来自函数内部抛出的异常,例如 read_item 的 404,那么除非你声明它,否则它不会出现在文档中。

FastAPI 文档

下一步

理解代码从上到下阅读 main.py,并逐个试用每个端点,包括会失败的请求。