FastAPI接口报‘str type expected’错误的排查与解决
问题:FastAPI接口接收JSON参数时提示类型错误
问题背景
我编写了一个获取Amazon RDS实例连接地址的函数,直接调用能正常返回结果,但通过FastAPI的POST接口,用Postman以JSON格式传参时,却收到了类型错误。用相同格式调用其他接收字符串的接口却能正常工作。
获取RDS连接地址的函数
def get_host(instance_name): """This function receives the name of an RDS instance and returns its connection endpoint""" client = boto3.client('rds', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_DEFAULT_REGION) instance = client.describe_db_instances(DBInstanceIdentifier=instance_name)['DBInstances'][0] endpoint = instance['Endpoint']['Address'] print(endpoint) return endpoint
FastAPI接口代码
@app.post("/host", tags=['host']) def get_host_with_api(instance_name: str = Body()): return {"endpoint": get_host(instance_name)}
触发的错误信息
当用Postman发送JSON {"instance_name":"instance10"}调用/host接口时,收到如下错误:
{ "detail": [ { "loc": [ "body" ], "msg": "str type expected", "type": "type_error.str" } ] }
补充更新
重新下载并启动Uvicorn服务后,问题已解决。
问题原因及解决方法
出现这个错误的核心是**Body()的使用方式不符合FastAPI的参数解析逻辑**:
- 当你写
instance_name: str = Body()时,FastAPI会期望请求体直接是一个纯字符串(比如请求体内容就是"instance10"),但你传入的是一个包含instance_name字段的JSON对象,自然会触发类型不匹配错误。
两种正确的处理方式
- 使用Pydantic模型定义请求体(推荐)
这种方式更规范,也方便后续扩展请求参数:
from pydantic import BaseModel class InstanceRequest(BaseModel): instance_name: str @app.post("/host", tags=['host']) def get_host_with_api(req: InstanceRequest): return {"endpoint": get_host(req.instance_name)}
- 给
Body()添加embed=True参数
如果不想定义模型,直接用embed=True告诉FastAPI从JSON对象中提取对应字段:
@app.post("/host", tags=['host']) def get_host_with_api(instance_name: str = Body(..., embed=True)): return {"endpoint": get_host(instance_name)}
你重启Uvicorn后问题解决,大概率是之前的代码修改没有被服务热加载,重启后新的修正代码才生效。
内容的提问来源于stack exchange,提问作者Andrea Aranda
相关产品推荐
相关产品推荐

