【FastAPI】接口传入参数怎么写?(以str为例)

在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}

在这个例子中,usernamepassword都是通过表单数据传递的字符串类型参数。

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模型来定义和验证请求体的结构。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值