来自 JavaScript 的 FastAPI 补丁请求出现问题

问题描述 投票:0回答:2

我使用 FastAPI 在 python 上创建了一个 REST 服务,我需要使用 Javascript 调用该 API。

这是我的 FastAPI 服务器:

class FieldUpdate(BaseModel):
item_id: Optional[int] = None
field_name: Optional[str] = None
field_value: Optional[str] = None

@router.patch("/update/item", response_model=FieldUpdate)
def update_item(body: FieldUpdate):
    item_id = body.item_id
    field_name = body.field_name
    field_value = body.field_value
    ctx_sle = get my current contenxt
    status = execute method after contenxt initialization (it has nothing to do with running the API)
    return status

在我的 JS 脚本中,我使用 fetch 尝试了这个请求

class FieldUpdate {
  constructor(item_id, field_name, field_value) {
    this.item_id = item_id;
    this.field_name = field_name;
    this.field_value = field_value;
  }

}
async function update_field_from_cell(field) {


const url = "http://127.0.0.1:8080/scriptlab/update/item";
  try {
    await fetch(url, {
      method: "PATCH",
      headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
      body: field
    })
      .then(function(response) {
        console.log(response.status);
        console.log(response.text());
      });
  } catch (error) {
    console.log(error);
  }

}

但是每次我运行此请求时,它都会返回

422 Unprocessable Entity
错误。您有什么建议可以解决这个问题吗?

javascript python rest fetch fastapi
2个回答
0
投票

如前所述,当接收到的有效负载与预期负载不匹配时,会抛出 422 Unprocessable Entity 错误。您的脚本发送一个 JS 对象,但应该发送一个 JSON 字符串,如下面的代码所示。另外,请确保在您的请求中使用正确的 URL(因为我注意到您使用的 URL 与 API 中的任何端点都不匹配)。请记得将 body 属性也更改为

body: json_data

async function update_field_from_cell(field) {
    var obj = {"item_id": field.item_id, "field_name": field.field_name, "field_value": field.field_value};
    json_data = JSON.stringify(obj);
    const url = "http://127.0.0.1:8000/update/item";
      try {
        await fetch(url, {
          method: "PATCH",
          headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
          body: json_data
        })
          .then(function(response) {
            console.log(response.status);
            console.log(response.text());
          });
      } catch (error) {
        console.log(error);
      }
}

0
投票

如果请求负载与 API 接受的实际负载不匹配,将抛出错误代码 422。

您使用的 Pydantic 模型仅验证并接受匹配的请求负载。

可在此处使用的示例有效负载:

1)

{
  "item_id":1, #integer
  "field_name": "some_name", #string
  "field_value": "some_value" #string
}
  1. 任何值都可以为“null”。因为您提到所有字段都是可选的:
{
  "item_id":null, #integer
  "field_name": "some_name", #string
  "field_value": null #string
}
© www.soinside.com 2019 - 2024. All rights reserved.