FastAPI 基本路由
引言
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它具有异步功能,并使用了标准 Python 类型提示。本文将详细介绍 FastAPI 的基本路由,包括路由的创建、使用以及一些高级特性。
路由的基本概念
在 FastAPI 中,路由是由路径(URL)和对应的处理函数组成的。当客户端发起请求时,FastAPI 会根据路径找到对应的处理函数,并调用它来处理请求。
创建路由
创建路由非常简单,只需使用 @app.route()
装饰器即可。以下是一个简单的例子:
from fastapi import FastAPI
app = FastAPI()
@app.route('/')
async def read_root():
return {"message": "Hello World"}
在上面的例子中,我们创建了一个根路由 /
,对应的处理函数是 read_root
。当访问根路径时,会返回 JSON 格式的消息 "Hello World"
。
路径参数
有时,我们需要根据路径中的参数来处理请求。FastAPI 允许我们使用路径参数来实现这一点。以下是一个例子:
from fastapi import FastAPI
app = FastAPI()
@app.route('/items/{item_id}')
async def read_item(item_id: int):
return {"item_id": item_id}
在上面的例子中,我们创建了一个路径参数为 item_id
的路由 /items/{item_id}
。当访问 /items/123
时,会返回 JSON 格式的消息 {"item_id": 123}
。
Query 参数
除了路径参数,FastAPI 还支持查询参数。查询参数位于 URL 的末尾,通常以 ?
开头。以下是一个例子:
from fastapi import FastAPI
app = FastAPI()
@app.get('/items/')
async def read_items(q: str = None):
if q:
return {"q": q}
return {"message": "Query parameter is required"}
在上面的例子中,我们创建了一个带有查询参数 q
的路由 /items/
。当访问 /items/?q=123
时,会返回 JSON 格式的消息 {"q": "123"}
。
路由的高级特性
路由嵌套
有时,我们需要将多个路由组织在一起,形成一个树状结构。FastAPI 允许我们使用嵌套路由来实现这一点。以下是一个例子:
from fastapi import FastAPI, Depends, HTTPException
app = FastAPI()
@app.group("/items/")
async def items():
pass
@app.get("/items/")
async def read_items():
return {"message": "This is the items list"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
在上面的例子中,我们创建了一个嵌套路由 /items/
,其中包含两个子路由:/items/
和 /items/{item_id}
。
路由中间件
路由中间件是一种用于处理请求和响应的函数。FastAPI 允许我们使用中间件来增强路由的功能。以下是一个例子:
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(f"Request: {request.method} {request.url}")
response = await call_next(request)
print(f"Response: {response.status_code}")
return response
在上面的例子中,我们创建了一个中间件 log_requests
,它会打印出请求的方法和 URL,以及响应的状态码。
总结
FastAPI 是一个功能强大的 Web 框架,其基本路由功能简单易用。通过本文的介绍,相信你已经对 FastAPI 的基本路由有了深入的了解。在实际开发中,你可以根据需求灵活运用路由的高级特性,构建出高性能、可扩展的 API 应用。