FastAPI教程-路由:绑定多个http方法(get、post) 作者:马育民 • 2026-08-05 17:38 • 阅读:10002 # 介绍 一个装饰器同时支持 `get`、`post` 等多个方法 # 方式1:多个装饰器 ```python @app.get("/demo") @app.post("/demo") async def demo(): return {"msg":"多装饰器实现GET+POST"} ``` # 方式2:@app.api_route `@app.get`/`post`本质就是`api_route`的封装,通过`methods`传列表即可一个接口同时接收 GET、POST。 ``` @app.api_route(path, methods=["GET","POST"]) ``` ### 例子 ```python from fastapi import FastAPI app = FastAPI() @app.api_route("/demo2", methods=["GET", "POST"]) async def demo2(): return {"msg": "支持GET和POST"} ``` **注意:**GET 请求**不能读取请求体(body)**,如果POST需要接收body参数,GET调用时不要传body,否则会报错。 --- # 方式3:多个路由函数 业务上更推荐,GET和POST语义不一样,逻辑往往不同,分开写可读性更好 ```python @app.get("/item") async def item_get(): return {"method":"get"} @app.post("/item") async def item_post(): return {"method":"post"} ``` 访问文档:`http://127.0.0.1:8000/docs`,可以看到该接口同时存在GET、POST两个操作。 原文出处:http://malaoshi.top/show_1GW3o8cA96BE.html