FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,它基于 Python 3.6 及以上版本。在 FastAPI 中发送 POST 请求,通常是指创建一个接口来接收客户端发送的 POST 请求。
以下是使用 FastAPI 处理 POST 请求的基本步骤:
首先,你需要安装 FastAPI 和 Uvicorn(一个 ASGI 服务器),可以使用 pip 进行安装:
1 |
pip install fastapi uvicorn |
创建一个 Python 文件,比如 main.py,并写入以下代码来创建一个 FastAPI 应用:
1 2 3 4 5 6 7 |
from fastapi import FastAPI
app = FastAPI()
@app.post("/items/") async def create_item(item: dict): return {"name": item["name"], "price": item["price"], "tax": item["price"] * 0.05} |
在这个例子中,我们定义了一个 POST 路由 /items/,它接收一个字典作为请求体,并返回一个包含商品名称、价格和税后价格的字典。
使用 Uvicorn 运行你的 FastAPI 应用:
1 |
uvicorn main:app --reload |
--reload 参数使得服务器在代码发生变化时自动重新加载。
你可以使用 curl 命令行工具、Postman 或编写代码(如使用 Python 的 requests 库)来发送 POST 请求。以下是使用 curl 的示例:
1 2 3 4 5 6 7 8 |
curl -X 'POST' \ 'http://127.0.0.1:8000/items/' \ -H 'accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "name": "Item1", "price": 10 }' |
这将向 /items/ 路由发送一个 POST 请求,并包含 JSON 格式的数据。
FastAPI 应用会接收到请求,并根据定义的路由和函数处理它,然后返回响应。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
IndexRouter = APIRouter(prefix="/graph", tags=["图谱管理"])
class IndexRouterMap:
@staticmethod @IndexRouter.post("/index_docs", summary="创建索引", description="创建索引") async def index_by_docs(kd: KnowledgeDocIndex):
return { "code": 0, "data": None, "msg": "成功", } |
1 2 3 4 5 |
class KnowledgeDocIndex(BaseModel): kb_name: str schema_id: int = 2 origNames: Optional[list[str]] = None run_id: Optional[str] = None |