FastAPI - 邮递员错误 422 无法处理的实体

我正在使用 FastAPI 发出 get/post/put/del 请求,这些请求在浏览器中都可以正常工作。我想用 Postman 做同样的事情;但是,我在尝试做 get 以外的任何事情时遇到了问题。以下是我得到的错误:

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

422 Unprocessable Entity 是确切的错误。

enter image description here

下面是我正在使用的代码:

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

stack overflow FastAPI - Postman error 422 Unprocessable Entity
原文答案

答案:

作者头像

您的端点需要 Item 作为 JSON ( body ) 数据,但您提供的屏幕截图显示您正在发送必填字段作为 Query 参数(使用 Postman 中的 Params 选项卡) ;因此,缺少 body 的错误。您应该将数据添加到 Postman 中 body 请求的 POST 中。为此,您应该转到 Body > raw ,然后从下拉列表中选择 JSON 以指示数据的格式。您的有效负载应如下所示:

{
 "name": "foo",
 "price": 1.50
}

另见 related answer 。如果您需要将 Item 模型的参数作为 Query 参数传递,则应使用 Depends() ,如 this answer (Method 2) 中所述。