标签: http-status-code-422

FastAPI 帖子无法识别我的参数

我通常使用 Tornado,并尝试迁移到 FastAPI。

假设我有一个非常基本的 API,如下所示:

@app.post("/add_data")
async def add_data(data):
    return data
Run Code Online (Sandbox Code Playgroud)

当我运行以下 Curl 请求时: curl http://127.0.0.1:8000/add_data -d 'data=Hello'

我收到以下错误:

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

所以我确信我错过了一些非常基本的东西,但我不知道那可能是什么。

python curl http-status-code-422 fastapi

12
推荐指数
1
解决办法
1万
查看次数

客户端错误请求400 vs 422

我已经阅读了很多关于正确的http状态代码的帖子和文章,以便返回客户端请求错误.其他人建议使用400,因为它已在RFC 7231中重新定义,但我不确定给出的示例是否涵盖了我脑海中的所有客户端错误,因为这些示例是语法.

400(错误请求)状态代码指示服务器由于被认为是客户端错误(例如,格式错误的请求语法,无效的请求
消息成帧或欺骗性请求路由)而不能或不会处理该请求.

我确实在rfc 7231的附录B中找到了这个陈述:

400(错误请求)状态代码已被放宽,因此
不限于语法错误.(第6.5.1节)

这是否意味着我可以将任何类型的客户端错误视为错误请求?将400用于客户端请求并在消息中指定更具体的错误会更好吗?


另一方面,其他人说最好使用422(不可处理的实体).虽然这更侧重于语义,但它仅在RFC 4918中列出,它是http/1.1的webDAV扩展.

的422(无法处理的实体)状态代码表示该服务器
理解的内容类型的请求实体(因此一个的
415(不支持的媒体类型)状态代码是不适当的),并且
所述请求实体的语法是正确的(因此400(错误的请求)
状态代码不合适)但无法处理包含的指令.例如,如果XML
请求主体包含格式正确(即语法正确)但
语义错误的XML指令,则可能发生此错误情况.

我可以使用此webDAV扩展代码来处理我的http请求吗?在422的情况下,我可以使用它,即使它不在核心http代码中.

我应该使用400或422来解决客户端错误吗?

以下是我想到的可能的客户端错误:

1.) Invalid parameter. The client provided parameters but are found invalid. Example: I said that the userId is 1, but when I checked there's no userId of 1. Another example of invalid parameter is wrong data type.
2.) Missing required parameters
3.) Let's say I need to hash a value based on given params and …
Run Code Online (Sandbox Code Playgroud)

error-handling http-status-codes http-error http-status-code-400 http-status-code-422

7
推荐指数
1
解决办法
3994
查看次数

如何从 422 Unprocessable Entity 响应中获取错误消息

我做了一个 api 调用,它返回给我这个

响应{protocol=http/1.1, code=422, message= Unprocessable Entity, url= https://someapi/endpoint }

在日志中,连同响应我得到以下内容:

{"message":"验证失败","errors":{"email":["已被占用"]}}

我正在开发一个具有个人资料创建功能的 Android 应用程序,我想将用户重定向回来,以便在我收到此响应时可以更改其电子邮件地址,但为此我需要获取并处理“错误”消息。

如何从错误正文中获取消息?我试过这样:

响应.消息()

但我只得到

不可处理的实体

error-handling android response retrofit http-status-code-422

7
推荐指数
1
解决办法
4755
查看次数

POST 数据不正确时的 HTTP 状态(使用不存在的资源 ID)

当我执行 POST 请求以创建新用户时返回正确 HTTP 状态是什么,但其参数之一不正确 - 我与用户数据一起包含的公司 ID 不存在于数据库中。

POST 数据:{用户名:'newuser',年龄:99,company_id:34 }

数据库中不存在 ID 为 34 的公司。

我在想这是否可能是:

  • 400,一种无效的数据,但它是有效但不存在的id
  • 404 - 但不清楚哪个资源不存在
  • 409,因为这是一种冲突,用户可以通过更改公司 ID 来解决这个问题
  • 422?
  • 或 500 - 因为这是一种数据库错误,而不允许存在不存在的 id

rest http-status-codes http-status-code-422

7
推荐指数
1
解决办法
5348
查看次数

请求正文中出现错误时的 HTTP 状态代码

有人可以澄清以下情况下我应该期待什么状态代码吗?例如,我正在发送具有以下正文格式的 POST 请求:

\n\n
{\n  "id": 321,\n  "username": "tombrown",\n  "email": "tombrown@gmail.com",\n  "password": "qwerty123",\n  "activated": true \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以问题是:

\n\n

1)如果我指定错误类型的数据,例如“id”:\xe2\x80\x9ctwoone\xe2\x80\x9d而不是int,服务器是否应该返回400,“activated”:\xe2\x80\x9cyes\xe2 \x80\x9d 而不是布尔值等。或者服务器应该在这里返回 422?

\n\n

2) \xe2\x80\x9cid\xe2\x80\x9d 值应该是 int,但实际上它是 long int,例如 9223372036854774700。

\n\n

3)正文中缺少某些字段,例如我尝试发送:

\n\n
{\n  "id": 321,\n  "username": "tombrown",\n  "activated": true \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

这些示例是否会导致 400、422 或其他一些选项?什么样的反应应该是正确的?

\n

http http-status-codes http-status-code-400 http-status-code-422

6
推荐指数
1
解决办法
9292
查看次数

422 错误中的“语义错误”或“语义错误”是什么意思?

我正在浏览一个高级的、与安全相关的 Ruby on Rails 教程,它在谈论 422 个 HTTP 响应,因为“客户端提交的请求格式正确,但语义上无效”。我还看到后一部分呈现为“语义错误”或“语义错误”。

在给出的示例中,这是由于 Rails 检查真实性令牌,但我明显觉得 HTTP 响应还有很多。

我将特别感谢已建立的社区成员对“语义无效/错误/错误”含义的规范定义。使请求格式良好但语义无效的一般规则是什么?

ruby-on-rails http httprequest http-status-code-422

5
推荐指数
1
解决办法
4744
查看次数

如何反序列化 422 无法处理的实体错误模型并将错误绑定到 asp.net core razor Pages 模型状态

我的Asp.Net Core 3.1 API返回422 Unprocessable Entity错误响应如下所示:

{
  "type": "https://test.com/modelvalidationproblem",
  "title": "One or more model validation errors occurred.",
  "status": 422,
  "detail": "See the errors property for details.",
  "instance": "/api/path",
  "traceId": "8000003f-0001-ec00-b63f-84710c7967bb",
  "errors": {
    "FirstName": [
      "The FirstName field is required."
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

如何反序列化此响应并将错误添加到模型验证错误中Asp.Net Core 3.1 Razor Pages

我尝试创建如下所示的模型,

错误模型:

{
  "type": "https://test.com/modelvalidationproblem",
  "title": "One or more model validation errors occurred.",
  "status": 422,
  "detail": "See the errors property for details.",
  "instance": "/api/path",
  "traceId": "8000003f-0001-ec00-b63f-84710c7967bb",
  "errors": …
Run Code Online (Sandbox Code Playgroud)

modelstate http-status-code-422 asp.net-core-webapi razor-pages asp.net-core-3.1

5
推荐指数
1
解决办法
6112
查看次数

FastAPI文件上传

我正在尝试使用请求将 JSON 数据+文件(二进制)上传到 FastAPI“POST”端点。

这是服务器代码:

@app.post("/files/")
async def create_file(
    file: bytes = File(...), fileb: UploadFile = File(...), timestamp: str = Form(...)
):
    return {
        "file_size": len(file),
        "timestamp": timestamp,
        "fileb_content_type": fileb.content_type,
    }
Run Code Online (Sandbox Code Playgroud)

这是客户端代码:

session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=0)
session.mount('http://', adapter)

jpg_image = open(IMG_PATH, 'rb').read()

timestamp_str = datetime.datetime.now().isoformat()
files = {
    'timestamp': (None, timestamp_str),
    'file': ('image.jpg', jpg_image),
}
request = requests.Request('POST',
                           FILE_UPLOAD_ENDPOINT,
                           files=files)
prepared_request = request.prepare()
response = session.send(prepared_request)
Run Code Online (Sandbox Code Playgroud)

服务器失败并显示

“POST /files/ HTTP/1.1” 422 无法处理的实体

python-requests http-status-code-422 fastapi uvicorn

5
推荐指数
1
解决办法
9966
查看次数

FastAPI:如何为特定路由自定义422异常?

如何仅针对 FastAPI 中的一条路由将 422 标准异常替换为自定义异常?

我不想替换应用项目,只想替换一条路线。我读了很多文档,但我不明白如何做到这一点。

我需要更改异常的路线示例422

from fastapi import APIRouter
from pydantic import BaseModel

router = APIRouter()


class PayloadSchema(BaseModel):
    value_int: int
    value_str: str


@router.post('/custom')
async def custom_route(payload: PayloadSchema):
    return payload
Run Code Online (Sandbox Code Playgroud)

python http-status-code-422 pydantic fastapi

5
推荐指数
1
解决办法
1819
查看次数

向 Redmine API 发送 POST 请求时如何修复“422 Unprocessable Entity”?

我正在尝试使用 redmine Rest api 创建一个 wiki 页面。身份验证已成功,但由于 422 错误,未创建 wiki 页面。

Redmine 文档说:“当尝试创建或更新属性参数无效或缺失的对象时,您将收到 422 Unprocessable Entity 响应。这意味着无法创建或更新该对象。”

但我似乎可以找出我哪里搞砸了。当我执行第二个请求“PUT REQUEST”时,问题出现了。

所以我们知道问题出在该部分的某个地方。

我的猜测是,它是文件路径或内容类型。

这就是我到目前为止所拥有的......

const wordDocument="C:\Users\adasani\Desktop\practice\RedmineApi/RedmineText.txt";

creatingWikiPage_Request(wordDocument);

function creatingWikiPage_Request(wordDocument) {

    axios({
        method: 'post',
        url: '<redmine_url>/uploads.json',
        headers: { 'Content-Type': 'application/octet-stream' },
        params: { 'key': '<api-key>' },
        data: wordDocument
    })
        .then(function (response) {
            console.log("succeeed--->  ");
            console.log(response.data.upload.token)
            axios({
                method: 'put',
                url: '<redmine_url>/projects/Testing/wiki/WikiTesting.json',
                headers: { 'Content-Type': 'application/octet-stream' },
                params: { 'key': '<api-key>' },
                data: {

                    "wiki_page": {
                        "text": "This is a wiki page with images, and …
Run Code Online (Sandbox Code Playgroud)

file-upload redmine redmine-api axios http-status-code-422

4
推荐指数
1
解决办法
9万
查看次数

使用 FastAPI 上传文件返回错误 422

我正在使用官方文档中的示例: https: //fastapi.tiangolo.com/tutorial/request-files/#import-file

服务器代码:

@app.post("/uploadfile")
async def create_upload_file(data: UploadFile = File(...)):
    print("> uploaded file:",data.filename)
    return {"filename": data.filename}
Run Code Online (Sandbox Code Playgroud)

客户端代码:

files = {'upload_file': open('config.txt', 'rb')}
resp = requests.post(
        url = URL,
        files = files)
print(resp.json())
Run Code Online (Sandbox Code Playgroud)

问题是服务器总是响应 422 错误:

{'detail': [{'loc': ['body', 'data'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我在服务器和客户端上都使用 Python 3,并且 python-multipart 包已经安装。

有人可以告诉我我做错了什么,我错过了什么,我应该如何修复代码?

非常感谢任何提示。

python file-upload http-status-code-422 fastapi

4
推荐指数
1
解决办法
4196
查看次数

为 422 错误生成错误页面

我目前正在为 500 和 404 错误生成动态错误页面。我想将其扩展为 422 错误。这是我们目前所拥有的。

配置/应用程序.rb

config.exceptions_app = self.routes
Run Code Online (Sandbox Code Playgroud)

控制器/errors_controller.rb

class ErrorsController < ApplicationController
  def not_found
    render status: 404
  end

  def internal_server_error
    render status: 500
  end

  def unacceptable
    render status: 422
  end
end
Run Code Online (Sandbox Code Playgroud)

路由文件

get '/404' => 'errors#not_found'
get '/500' => 'errors#internal_server_error'
get '/422' => 'errors#unacceptable'
Run Code Online (Sandbox Code Playgroud)

public/422.html 页面已被删除。错误视图页面已创建,但为简洁起见省略。当出现 404 或 500 错误时,会显示错误页面。但是,当我收到 422 错误时,我会看到以下错误页面。

在此处输入图片说明

我已经看到许多实施这种相同方法的教程并且它有效。但是,我收到的是生成的 Rails 错误,而不是我创建的错误页面。出了什么问题,我该如何解决?

我看过的教程:

ruby routes ruby-on-rails ruby-on-rails-4 http-status-code-422

2
推荐指数
1
解决办法
1901
查看次数

FastApi:422 无法处理的实体

我在尝试接受迂腐模型时遇到此错误。经过一段时间的调试后,我相信问题出在接受上CodeCreate

悬垂模型

class BaseCode(BaseModel):
    index: Optional[int] = Field(None)
    email: EmailStr
    gen_time: datetime
    expire_time: datetime


class CodeCreate(BaseCode):
    code: int
    used_time: Optional[datetime] = Field(None)

    class Config:
        orm_mode = True

class Message(BaseModel):
    message: str
Run Code Online (Sandbox Code Playgroud)

代码 ORM

class Code(Base):
    __tablename__ = 'code'

    index = Column(Integer, primary_key=True, autoincrement=True)
    code = Column(Integer)
    email = Column(String, ForeignKey('user.email'))
    gen_time = Column(DateTime)
    expire_time = Column(DateTime)
    used_time = Column(DateTime, nullable=True)
Run Code Online (Sandbox Code Playgroud)

处理程序

@app.post('/verify-code', response_model=schemas.Message, responses={404: {"model": schemas.Message}, 406: {"model": schemas.Message}})
async def verify_code(code: schemas.CodeCreate, response: Response, device_name: str = Body(..., …
Run Code Online (Sandbox Code Playgroud)

python http-status-code-422 pydantic fastapi

1
推荐指数
1
解决办法
4万
查看次数