如何使用Python FastAPI框架来实现POST请求处理?传入数组数据
时间: 2024-11-03 22:17:26 浏览: 50
在FastAPI中,要处理POST请求并接收数组数据,你需要定义一个路由(endpoint),然后使用`Body`装饰器指定期望的数据结构。这里是一个简单的例子:
首先,确保安装了FastAPI和Uvicorn(用于启动服务器)。你可以通过运行`pip install fastapi uvicorn`来安装。
1. 引入所需的模块:
```python
from fastapi import FastAPI, Depends, HTTPException, Body
```
2. 创建FastAPI实例:
```python
app = FastAPI()
```
3. 定义一个函数来处理POST请求,假设你要接收的是JSON格式的数组数据:
```python
def handle_post_array(data: list[dict]) -> dict:
# 这里可以添加对数据的验证、处理逻辑等
return {"message": "Received array data:", "data": data}
```
4. 使用`@app.post`装饰器创建路由,并将上面的函数绑定到该路由:
```python
@app.post("/post-array")
async def post_array_endpoint(data: list[dict] = Body(...)):
try:
result = handle_post_array(data)
return result
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
```
在这个例子中,`Body(...)`会自动解析JSON内容并转换为Python列表。如果数据不符合预期,FastAPI会抛出`HTTPException`。
要测试这个端点,你可以使用curl或者Postman发送一个包含数组数据的POST请求到`http://localhost:8000/post-array`(假设你的Uvicorn服务在本地8000端口运行)。
阅读全文
相关推荐
















