📜  使用 FastAPI 创建第一个 REST API(1)

📅  最后修改于: 2023-12-03 15:22:11.116000             🧑  作者: Mango

使用 FastAPI 创建第一个 REST API

FastAPI 是一个快速、现代化、基于 Python3.6+ 的 Web 框架,用于构建 API。它具有以下优点:

  • 快速:相比其他 Python Web 框架,FastAPI 更快,因为它使用了 Starlette(一个高性能的 ASGI 框架)和 Pydantic(一个用于数据验证和序列化的库)。
  • 快速编写文档:FastAPI 使用 OpenAPI 和 JSON Schema 标准自动生成 API 文档。
  • 简洁而直观:FastAPI 是使用 Python 类型提示(type hints)而不是字符串来进行声明的,使得代码更简洁且易于维护。此外,FastAPI 还提供了自动数据验证、自动文档生成和自动代码生成等功能。

在本文中,我们将使用 FastAPI 来创建一个简单的 CRUD(创建、读取、更新、删除) API。

安装 FastAPI 和 Uvicorn

首先,我们需要安装 FastAPI 和 Uvicorn(一个快速的 ASGI 服务器):

$ pip install fastapi uvicorn
创建一个 FastAPI 应用程序

创建一个名为 main.py 的文件,并输入以下代码:

from fastapi import FastAPI

app = FastAPI()

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

这个应用程序有一个根路由 /,当访问这个路由时,它会返回一个 "Hello World" 消息。

运行 FastAPI 应用程序

现在,我们可以使用 Uvicorn 启动应用程序。在命令行中输入以下命令:

$ uvicorn main:app --reload

然后我们可以在浏览器中访问 http://127.0.0.1:8000/,就可以看到我们刚才定义的消息:Hello World。

添加更多的路由

接下来我们将添加一些 CRUD 路由,用于创建、读取、更新和删除文章。

from fastapi import FastAPI

app = FastAPI()

# 创建文章
@app.post("/articles/")
async def create_article(title: str, content: str):
    return {"title": title, "content": content}

# 获取文章
@app.get("/articles/{article_id}")
async def read_article(article_id: int):
    return {"article_id": article_id}

# 更新文章
@app.put("/articles/{article_id}")
async def update_article(article_id: int, title: str, content: str):
    return {"article_id": article_id, "title": title, "content": content}

# 删除文章
@app.delete("/articles/{article_id}")
async def delete_article(article_id: int):
    return {"article_id": article_id, "message": "Article deleted successfully."}

我们定义了四个路由:

  1. POST /articles/ — 创建文章
  2. GET /articles/{article_id} — 获取文章
  3. PUT /articles/{article_id} — 更新文章
  4. DELETE /articles/{article_id} — 删除文章

现在我们可以使用 curl 或任何 API 测试工具来测试这些路由了。

API 文档

FastAPI 自动创建 API 文档,我们可以在浏览器中访问 http://127.0.0.1:8000/docs 来查看文档。这个页面包括了所有路由的请求和响应模型,甚至可以在页面上测试这些路由。

总结

FastAPI 是一个快速、现代化的 Python Web 框架,用于构建 API。它具有自动生成 API 文档、自动数据验证、自动代码生成等功能,并使用 Python 类型提示(type hints)使代码更简洁易读。在本文中,我们创建了一个简单的 CRUD API 并学习了如何自动生成 API 文档。