FastAPI 安装

FastAPI 依赖 Python 3.8 及更高版本。

安装 FastAPI 很简单,这里我们使用 pip 命令来安装。

									pip install fastapi
								

另外我们还需要一个 ASGI 服务器,生产环境可以使用 Uvicorn 或者 Hypercorn:

									pip install "uvicorn[standard]"
								

这样我们就安装完成了。

运行第一个 FastAPI 应用

创建一个名为 main.py 的文件,添加以下代码:

实例

from fastapi import FastAPI

app = FastAPI ( )

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

在命令行中运行以下命令以启动应用:

									uvicorn main:app --reload
								

现在,打开浏览器并访问 http://127.0.0.1:8000 ,你应该能够看到 FastAPI 自动生成的交互式文档,并在根路径 ("/") 返回的 JSON 响应。