跳到内容

快速入门

最简单的 FastAPI 文件可能如下所示

from fastapi import FastAPI

app = FastAPI()


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

将其复制到 `main.py` 文件中。

运行实时服务器

$ <font color="#4E9A06">fastapi</font> dev <u style="text-decoration-style:solid">main.py</u>

  <span style="background-color:#009485"><font color="#D3D7CF"> FastAPI </font></span>  Starting development server 🚀

             Searching for package file structure from directories
             with <font color="#3465A4">__init__.py</font> files
             Importing from <font color="#75507B">/home/user/code/</font><font color="#AD7FA8">awesomeapp</font>

   <span style="background-color:#007166"><font color="#D3D7CF"> module </font></span>  🐍 main.py

     <span style="background-color:#007166"><font color="#D3D7CF"> code </font></span>  Importing the FastAPI app object from the module with
             the following code:

             <u style="text-decoration-style:solid">from </u><u style="text-decoration-style:solid"><b>main</b></u><u style="text-decoration-style:solid"> import </u><u style="text-decoration-style:solid"><b>app</b></u>

      <span style="background-color:#007166"><font color="#D3D7CF"> app </font></span>  Using import string: <font color="#3465A4">main:app</font>

   <span style="background-color:#007166"><font color="#D3D7CF"> server </font></span>  Server started at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font>
   <span style="background-color:#007166"><font color="#D3D7CF"> server </font></span>  Documentation at <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000/docs</u></font>

      <span style="background-color:#007166"><font color="#D3D7CF"> tip </font></span>  Running in development mode, for production use:
             <b>fastapi run</b>

             Logs:

     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Will watch for changes in these directories:
             <b>[</b><font color="#4E9A06">&apos;/home/user/code/awesomeapp&apos;</font><b>]</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Uvicorn running on <font color="#729FCF"><u style="text-decoration-style:solid">http://127.0.0.1:8000</u></font> <b>(</b>Press CTRL+C
             to quit<b>)</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Started reloader process <b>[</b><font color="#34E2E2"><b>383138</b></font><b>]</b> using WatchFiles
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Started server process <b>[</b><font color="#34E2E2"><b>383153</b></font><b>]</b>
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Waiting for application startup.
     <span style="background-color:#007166"><font color="#D3D7CF"> INFO </font></span>  Application startup complete.

在输出中,会有一行类似的内容

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

该行显示了应用程序在本地机器上运行的 URL。

检查它

在浏览器中打开 http://127.0.0.1:8000

你将看到如下 JSON 响应

{"message": "Hello World"}

交互式 API 文档

现在访问 http://127.0.0.1:8000/docs

你将看到自动生成的交互式 API 文档(由 Swagger UI 提供)

Swagger UI

备选 API 文档

现在,访问 http://127.0.0.1:8000/redoc

你将看到备选的自动文档(由 ReDoc 提供)

ReDoc

OpenAPI

FastAPI 使用定义 API 的 OpenAPI 标准,为你所有的 API 生成一个“模式”。

“模式”

“模式”是对某物的定义或描述。它不是实现该定义的代码,而仅仅是一个抽象的描述。

API “模式”

在本例中,OpenAPI 是一个规定如何定义 API 模式的规范。

此模式定义包括你的 API 路径、它们可能接受的参数等。

数据“模式”

术语“模式”也可以指某些数据的形状,例如 JSON 内容。

在这种情况下,它将意味着 JSON 属性及其数据类型等。

OpenAPI 和 JSON Schema

OpenAPI 为你的 API 定义了一个 API 模式。该模式包括使用 JSON Schema(JSON 数据模式标准)定义 API 发送和接收的数据(或“模式”)。

查看 openapi.json

如果你好奇原始的 OpenAPI 模式是什么样子,FastAPI 会自动生成一个 JSON(模式),其中包含你所有 API 的描述。

你可以在以下地址直接查看它:http://127.0.0.1:8000/openapi.json

它将显示一个以如下内容开头的 JSON

{
    "openapi": "3.1.0",
    "info": {
        "title": "FastAPI",
        "version": "0.1.0"
    },
    "paths": {
        "/items/": {
            "get": {
                "responses": {
                    "200": {
                        "description": "Successful Response",
                        "content": {
                            "application/json": {



...

OpenAPI 有何用途

OpenAPI 模式是所包含的两个交互式文档系统背后的动力。

还有数十种替代方案,所有这些都基于 OpenAPI。你可以轻松地将这些替代方案中的任何一个添加到使用 FastAPI 构建的应用程序中。

你还可以用它来自动生成与你的 API 通信的客户端代码。例如,前端、移动或物联网应用程序。

回顾,一步一步来

步骤 1: 导入 FastAPI

from fastapi import FastAPI

app = FastAPI()


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

FastAPI 是一个 Python 类,它提供了你 API 的所有功能。

技术细节

FastAPI 是一个直接继承自 `Starlette` 的类。

你也可以在 FastAPI 中使用所有 Starlette 的功能。

步骤 2: 创建 `FastAPI` “实例”

from fastapi import FastAPI

app = FastAPI()


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

这里的 `app` 变量将是 `FastAPI` 类的一个“实例”。

这将是创建所有 API 的主要交互点。

步骤 3: 创建路径操作

路径

这里的“路径”指的是 URL 中从第一个 `/` 开始的最后一部分。

因此,在像这样子的 URL 中

https://example.com/items/foo

……路径将是

/items/foo

信息

“路径”也通常被称为“端点”或“路由”。

在构建 API 时,“路径”是分离“关注点”和“资源”的主要方式。

操作

这里的“操作”指的是 HTTP“方法”之一。

其中之一

  • POST
  • GET
  • PUT
  • DELETE

……以及其他更不常用的方法

  • OPTIONS
  • HEAD
  • PATCH
  • TRACE

在 HTTP 协议中,你可以使用这些“方法”中的一个(或多个)与每个路径进行通信。


在构建 API 时,通常会使用这些特定的 HTTP 方法来执行特定操作。

通常你使用

  • POST:创建数据。
  • GET:读取数据。
  • PUT:更新数据。
  • DELETE:删除数据。

因此,在 OpenAPI 中,每个 HTTP 方法都被称为一个“操作”。

我们也将它们称为“操作”。

定义*路径操作装饰器*

from fastapi import FastAPI

app = FastAPI()


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

`@app.get("/")` 告诉 FastAPI,正下方的函数负责处理发送到以下地址的请求

  • 路径 `/`
  • 使用 get 操作

`@装饰器` 信息

Python 中 `@something` 的语法被称为“装饰器”。

你把它放在函数上方。就像一顶漂亮的装饰帽(我猜这个术语就是由此而来)。

“装饰器”会获取下面的函数并对其进行一些操作。

在我们的例子中,这个装饰器告诉 FastAPI,下面的函数对应于 路径 `/` 和 操作 `get`。

它就是“路径操作装饰器”。

你也可以使用其他操作

  • @app.post()
  • @app.put()
  • @app.delete()

以及更不常用的方法

  • @app.options()
  • @app.head()
  • @app.patch()
  • @app.trace()

提示

你可以随意使用每个操作(HTTP 方法)。

FastAPI 不强制规定任何特定含义。

这里的信息作为指导,而非要求。

例如,在使用 GraphQL 时,你通常仅使用 `POST` 操作来执行所有动作。

步骤 4: 定义**路径操作函数**

这就是我们的“路径操作函数

  • 路径: 是 `/`。
  • 操作: 是 `get`。
  • 函数: 是“装饰器”下方的函数(在 `@app.get("/")` 下方)。
from fastapi import FastAPI

app = FastAPI()


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

这是一个 Python 函数。

每当 FastAPI 收到对 URL “`/`” 的 `GET` 操作请求时,都会调用此函数。

在这种情况下,它是一个 `async` 函数。


你也可以将其定义为普通函数,而不是 `async def`

from fastapi import FastAPI

app = FastAPI()


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

注意

如果你不了解其区别,请查看 异步:“着急吗?”

步骤 5: 返回内容

from fastapi import FastAPI

app = FastAPI()


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

你可以返回 `dict`、`list`、`str`、`int` 等单一值。

你也可以返回 Pydantic 模型(稍后会详细介绍)。

还有许多其他对象和模型将自动转换为 JSON(包括 ORM 等)。尝试使用你喜欢的设计,很可能它们已经得到支持。

总结

  • 导入 `FastAPI`。
  • 创建一个 `app` 实例。
  • 使用 @app.get("/") 等装饰器编写一个路径操作装饰器
  • 定义一个路径操作函数;例如,def root(): ...
  • 使用命令 `fastapi dev` 运行开发服务器。