FastAPI框架中的路由用来匹配HTTP请求方法和路径,并将请求交给对应的处理函数进行处理和响应,这篇笔记我们学习FastAPI框架中路由的用法。
在FastAPI框架中,路由的创建非常简单,只需要使用app.get()
、app.post()
等装饰器,并传入路径和处理函数即可。例如,创建一个简单的GET路由:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def root():
return {'message': 'Hello, world!'}
上面代码中,我们创建了一个对应于GET /
路径的路由。
下面例子我们基于路径参数创建路由。
from fastapi import FastAPI
app = FastAPI()
@app.get('/user/{user_id:str}')
async def root(user_id: str):
return {'message': user_id}
该路由会匹配形如/user/1
、/user/aaa
等路径,但不会匹配形如/user/1/detail
的路径。
此外我们要注意这个路由匹配也是基于类型的,如果我们将路由匹配的类型改为int
,那么它将只匹配形如/user/1
的路径,而不会匹配形如/user/aaa
的路径,下面是一个例子。
from fastapi import FastAPI
app = FastAPI()
@app.get('/user/{user_id:int}')
async def root(user_id: int):
return {'message': user_id}
此时仅有整数类型的user_id
能够成功进行路由匹配。
我们也可以基于路径参数实现多级路径的匹配,下面是一个例子。
from fastapi import FastAPI
app = FastAPI()
@app.get('/{path:path}')
async def root(path: str):
return {'message': path}
代码中,我们定义路由为/{path:path}
,它表示路径参数path
是path
类型,此时无论我们访问/a
或是/a/b
该路由都能进行匹配,并将子路径作为参数传入处理函数中。
在FastAPI框架中,路由可以进行分组,将相关的路由放在一起更方便管理和维护。路由分组需要用到APIRouter
对象来实现,下面是一个例子。
from fastapi import FastAPI, APIRouter
app = FastAPI()
# 创建路由分组
demo_router = APIRouter()
@demo_router.get('/')
async def root():
"""基于路由分组创建的处理函数"""
return {'message': 'Hello, world!'}
# 注册路由分组到app对象
app.include_router(demo_router, prefix='/demo')
此时我们访问/demo/
即可进入root()
处理函数中。
注意:注册路由分组必须在定义路由之后进行,否则处理函数的无法生效的。
FastAPI支持HTTP协议的所有方法,常用的有GET、POST、PUT、DELETE等,这些HTTP方法对应路由的装饰器名。下面例子代码中,我们针对GET /
和POST /
两种请求方法进行了不同的响应处理。
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def handle_get():
return {'message': 'GET'}
@app.post('/')
async def handle_post():
return {'message': 'POST'}
代码中,虽然两条路由匹配的都是/
路径,但它们匹配不同的HTTP请求方法,因此不会相互冲突。