在FastAPI中,接口传参通常是通过路径参数(Path Parameters)、查询参数(Query Parameters)、表单数据(Form Data)、请求体(Body)等方式进行的。如果你想在FastAPI接口中通过某种方式接收一个字符串(str
)类型的参数,以下是一些常见的场景和示例。
1. 查询参数(Query Parameters)
查询参数是附加在URL后面的键值对,用于传递额外的信息。在FastAPI中,你可以使用Query
参数类型注解来指定一个查询参数为字符串类型。
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(None, title="Query string", description="Query string for the items to search in the database that have a good match")):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
在这个例子中,q
是一个查询参数,它默认为None
,但你可以通过传递一个查询字符串(如?q=somequery
)来指定它。
2. 路径参数(Path Parameters)
路径参数是URL路径的一部分,用于指定资源或数据的特定标识符。在FastAPI中,路径参数通过位置参数(不带注解)或带有Path
注解的参数来定义。
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: str = Path(..., title="The ID of the item to get", description="Unique item identifier")):
return {"item_id": item_id}
在这个例子中,item_id
是一个路径参数,它必须被提供,因为使用了Path(...)
,并且FastAPI会确保这个参数是字符串类型。
3. 表单数据(Form Data)
当处理HTML表单提交或类似场景时,你可能会接收到表单数据。FastAPI使用Form
来接收表单数据中的字段。
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username, "password": password}
在这个例子中,username
和password
都是通过表单数据传递的字符串类型参数。
4. 请求体(Body)
对于更复杂的输入,你可能想要使用请求体来接收数据。这通常通过Pydantic模型来实现,但你也可以直接在函数参数中接收JSON数据(如果内容类型是application/json
)。
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return item
# 或者,如果你只是想要一个字符串类型的JSON体
@app.post("/text/")
async def receive_text(text: str):
# 注意:这在实际应用中可能不是最佳实践,因为通常我们会期望JSON对象
return {"text": text}
然而,直接接收一个字符串作为请求体(如上例中的receive_text
函数)通常不是最佳实践,因为HTTP请求体通常期望是JSON或类似的结构化格式。如果你的确需要这样做,确保客户端以正确的方式发送数据(例如,使用Content-Type: text/plain
而不是application/json
)。不过,在大多数情况下,你应该使用Pydantic模型来定义和验证请求体的结构。