FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 类型提示驱动。它旨在快速开发,具有高性能,并且易于学习和使用。本篇文章将带您通过一个实例,详细讲解如何入门 FastAPI,并轻松掌握高效编程技巧。
快速搭建 FastAPI 项目
首先,确保您的 Python 环境已安装。接下来,按照以下步骤创建一个基本的 FastAPI 应用:
- 安装 FastAPI 和 Uvicorn
pip install fastapi uvicorn
- 创建项目目录和文件
创建一个名为 my_fastapi 的目录,并在其中创建一个名为 main.py 的文件。
- 编写 FastAPI 应用代码
在 main.py 文件中,编写以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
这段代码定义了一个简单的 FastAPI 应用,其中包含一个根路径 / 的 GET 请求处理器。
- 运行应用
使用 Uvicorn 运行应用:
uvicorn main:app --reload
在浏览器中访问 http://127.0.0.1:8000/,您将看到响应的 JSON 数据。
FastAPI 路由和视图函数
FastAPI 使用路由和视图函数来处理请求。以下是创建路由和视图函数的示例:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
在这个例子中,我们创建了一个名为 /items/{item_id} 的路由,它接受一个路径参数 item_id。如果 item_id 等于 404,则会抛出一个 404 错误。
FastAPI 响应和请求
FastAPI 支持多种响应类型,包括 JSON、XML、HTML 等。以下是一个示例,演示如何返回 JSON 响应:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
在这个例子中,我们创建了一个 /items/ 路由,它接受一个 POST 请求,并返回一个 JSON 响应。
对于请求,FastAPI 允许您使用 Pydantic 模型来验证和解析请求体。以下是一个示例:
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return item
在这个例子中,我们定义了一个 Item 模型,它包含 name、description、price 和 tax 字段。当创建一个新项目时,FastAPI 会自动验证和解析请求体。
总结
通过以上实例,您已经了解了 FastAPI 的基本概念和用法。FastAPI 提供了丰富的功能,可以帮助您轻松构建高效、可扩展的 API。希望本篇文章能帮助您入门 FastAPI,并轻松掌握高效编程技巧。
