fastapi如何返回422
时间: 2023-09-26 07:07:54 浏览: 43
在 FastAPI 中,可以通过抛出 `HTTPException` 异常来返回任何 HTTP 状态码。对于返回 422 状态码,可以像这样定义一个异常:
```python
from fastapi import HTTPException
class UnprocessableEntity(HTTPException):
def __init__(self, detail: str):
super().__init__(status_code=422, detail=detail)
```
在路由处理函数中,如果需要返回 422 状态码,可以像这样抛出异常:
```python
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return PlainTextResponse(str(exc), status_code=422)
@app.post("/items/")
async def create_item(item: Item):
if item.price < 0:
raise UnprocessableEntity(detail="Price cannot be negative.")
return {"item": item}
```
在上面的代码中,当 `create_item` 路由处理函数中的 `item.price` 属性为负数时,会抛出 `UnprocessableEntity` 异常,从而返回 422 状态码和错误信息。如果需要自定义错误信息,可以在异常的构造函数中传递一个字符串参数作为详细信息(detail)。