FastAPI 入门

什么是 FastAPI? 根据其官方网站的介绍: FastAPI 是一个现代、高性能的 Web 框架,基于标准 Python 类型提示,使用 Python 3.8 及以上版本构建 API。 使用 FastAPI 编写 Hello World 安装 系统要求 Python 3.8 及以上版本 安装 FastAPI 1 pip install fastapi 安装 ASGI 服务器 1 pip install "uvicorn[standard]" 定义 FastAPI 应用 创建一个名为 main.py 的文件,并添加: 1 2 3 4 5 from typing import Union from fastapi import FastAPI app = FastAPI() 创建 API 端点 在 main.py 中添加以下两个端点: 1 2 3 4 5 6 7 8 @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} 带自动验证功能的 API 端点 最终代码如下: ...

December 1, 2023 · 2 min · 278 words · Justin Hu