Fastapi接口列表怎么传参数
时间: 2024-01-30 11:03:06 浏览: 29
在 FastAPI 中,接口可以通过多种方式传递参数:
1. 路径参数:路径参数是指在请求 URL 中的一部分。使用`{}`将参数名称包括在路径中,并在函数中使用相同的名称来访问它们。例如:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
```
2. 查询参数:查询参数是指在请求 URL 的后面,使用 `?` 分隔的参数。例如:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
```
3. 请求体参数:请求体参数可以是 JSON、表单数据等。需要使用 Pydantic 模型来解析请求体参数。例如:
```python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = None
@app.post("/items/")
async def create_item(item: Item):
return item
```
以上是使用 FastAPI 传递参数的几种方式,你可以根据需要灵活选择。