配置API
多个装饰器装饰一个视图函数
如果一个视图函数需要同时支持多个请求地址的访问,可以使用多个装饰器装饰同一个视图函数。示例:
@app.get("/")
@app.get("/index")
def root():
return {"msg": "hello world"}
一个URL配置多个HTTP请求方法
通过@app.api_route支持配置视图函数使用不同的HTTP请求方法
@app.get("/",
tags=["test"],
summary="root url",
description="fastapi quickstart",
response_class=JSONResponse)
@app.api_route("/index", methods=["GET", "POST"])
def index():
return {"msg": "Hello World"}
处理路径参数
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id": item_id}
- 声明路径参数的类型
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
如果存在@app.get("/items/item_id")和@app.get("/items/{item_id}")两条路由,一个静态,一个动态。同时访问时"/items/item_id"时,会按照谁先定义就优先访问谁的顺序来访问。如果先定义静态路由,就先访问静态路由。