首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FastAPI -邮递员错误422不可处理实体

FastAPI -邮递员错误422不可处理实体
EN

Stack Overflow用户
提问于 2022-03-15 20:20:38
回答 1查看 2.7K关注 0票数 1

我正在使用FastAPI来发出get/post/put/del请求,这些请求在浏览器中都能很好地工作。我想使用邮递员做同样的事情;然而,我遇到了一个问题,试图做的不是GET。下面是我遇到的错误:

代码语言:javascript
运行
复制
{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

422 Unprocessable Entity是精确的错误。

下面是我使用的代码:

代码语言:javascript
运行
复制
from lib2to3.pytree import Base
from fastapi import FastAPI, Path, Query, HTTPException, status, File, Form
from typing import Optional, Dict, Type
from pydantic import BaseModel
import inspect

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    brand: Optional[str] = None


class UpdateItem(BaseModel):
    name: Optional[str] = None
    price: Optional[float] = None
    brand: Optional[str] = None


inventory = {}

@app.get("/get-item/{item_id}")
def get_item(item_id: int = Path(None, description = "The ID of the item")):
    if item_id not in inventory:
        raise HTTPException(status_code = 404, detail = "Item ID not found")
    return inventory[item_id]
    

@app.get("/get-by-name/")
def get_item(name: str = Query(None, title = "Name", description = "Test")):
    for item_id in inventory:
        if inventory[item_id].name == name:
            return inventory[item_id]
    # return {"Data": "Not found"}
    raise HTTPException(status_code = 404, detail = "Item ID not found")


@app.post("/create-item/{item_id}")
def create_item(item_id: int, item: Item):
    if item_id in inventory:
        raise HTTPException(status_code = 400, detail = "Item ID already exists")

    inventory[item_id] = item
    print(type(item))
    return inventory[item_id]
    

@app.put("/update-item/{item_id}")
def update_item(item_id: int, item: UpdateItem):
    if item_id not in inventory:
        # return {"Error": "Item does not exist"}
        raise HTTPException(status_code = 404, detail = "Item ID not found")

    if item.name != None:
        inventory[item_id].name = item.name
    if item.brand != None:
        inventory[item_id].brand = item.brand
    if item.price != None:
        inventory[item_id].price = item.price
    
    return inventory[item_id]


@app.delete("/delete-item/{item_id}")
def delete_item(item_id: int = Query(..., description="ID of item you want to delete", ge=0)):
    if item_id not in inventory:
        # return {"Error": "ID does not exist"}
        raise HTTPException(status_code = 404, detail = "Item ID not found")
    del inventory[item_id]
    return {"Success": "Item deleted"}

我尝试了这个可能的解决方案,但没有成功:https://github.com/tiangolo/fastapi/issues/2387

EN

回答 1

Stack Overflow用户

发布于 2022-03-15 21:07:22

您的端点期望Item作为JSON (body)数据,但是您提供的屏幕截图显示,您正在以Query参数的形式发送所需的字段(使用Postman中的Params选项卡);因此,body丢失了错误。相反,您应该在Postman中将数据添加到POST请求的POST中。为此,您应该转到Body > raw,并从下拉列表中选择JSON以指示数据的格式。您的有效载荷应该如下所示:

代码语言:javascript
运行
复制
{
 "name": "foo",
 "price": 1.50
}

参见相关答案herehere。如果需要将Item模型的参数作为Query参数传递,则应该使用Depends(),如this answer (Method 2)中所述。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71488533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档