-
FastAPI has a default response doc for 422, {
'code': 0,
'msg': 'hello',
'data': <object>
} and I found the code in fastapi/openapi/utils http422 = str(HTTP_422_UNPROCESSABLE_ENTITY)
if (all_route_params or route.body_field) and not any(
[
status in operation["responses"]
for status in [http422, "4XX", "default"]
]
):
operation["responses"][http422] = {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {"$ref": REF_PREFIX + "HTTPValidationError"}
}
},
}
if "ValidationError" not in definitions:
definitions.update(
{
"ValidationError": validation_error_definition,
"HTTPValidationError": validation_error_response_definition,
}
) I think many application will need this feature. |
Beta Was this translation helpful? Give feedback.
Replies: 19 comments 18 replies
-
1, catch exception and rewrite response def register_exception(app)
@app.exception_handler(ValidationError)
async def db_validation_exception_handle(request: Request, exc: ValidationError):
exc_str = '|'.join(exc.args)
content = {'code': 0, 'msg': exc_str, 'data': None}
return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY) 2, router, api class ValidatorError(BaseModel):
code: int = 0
msg: str = ''
data: Any = None
error_response = {
...
422: {
'model': ValidatorError,
'description': '参数验证错误的返回值 data=null',
}
}
@router.get('', response_model=YourSchema, status_code=YourCode, responses=error_response)
def func():
... |
Beta Was this translation helpful? Give feedback.
-
@panla |
Beta Was this translation helpful? Give feedback.
-
My solution is inheriting |
Beta Was this translation helpful? Give feedback.
-
I want disable 200 http code, because my api never return this code, is a post request. |
Beta Was this translation helpful? Give feedback.
-
@DionVitor what do you mean ? Regardless of the method you need to send an http status code back |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
The purpose of the swagger api definition is to include all the possible responses for an endpoint |
Beta Was this translation helpful? Give feedback.
-
Exactly!! 200 status it's not possible in my post endpoint. |
Beta Was this translation helpful? Give feedback.
-
If your endpoint returns a diffferent code you can configure your response code with |
Beta Was this translation helpful? Give feedback.
-
@kounelios13 I think you misunderstood what @DionVitor meant. I have probably a similar problem. I need to return the validation error with a different status code, but 422 is still in the OpenAPI if I override the ValidationError in FastAPI |
Beta Was this translation helpful? Give feedback.
-
My newest solution: app = FastAPI()
def custom_openapi():
if not app.openapi_schema:
app.openapi_schema = get_openapi(
title=app.title,
version=app.version,
openapi_version=app.openapi_version,
description=app.description,
terms_of_service=app.terms_of_service,
contact=app.contact,
license_info=app.license_info,
routes=app.routes,
tags=app.openapi_tags,
servers=app.servers,
)
for _, method_item in app.openapi_schema.get('paths').items():
for _, param in method_item.items():
responses = param.get('responses')
# remove 422 response, also can remove other status code
if '422' in responses:
del responses['422']
return app.openapi_schema
app.openapi = custom_openapi Hope this is useful. @vanntile @kounelios13 |
Beta Was this translation helpful? Give feedback.
-
thank you |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help and discussion all! ☕ |
Beta Was this translation helpful? Give feedback.
-
The solutions above feel like a lot of boiler plate. The 422 response code is a reasonable default behavior, but the framework assuming that everyone wants this default behavior doest not feel reasonable. @JKearnsl solution would work, but it would be nice to have a way to inject this behavior instead of forcing people to monkey patch it if they don't want it. |
Beta Was this translation helpful? Give feedback.
-
this is my code import json from fastapi import (APIRouter, FastAPI, HTTPException, Request, Response,Query, from .authentication import Auth from fastapi import FastAPI from fastapi.openapi.utils import get_openapi security = HTTPBearer() app = FastAPI() router = APIRouter(
})
def custom_openapi(): app.openapi = custom_openapi after adding the code then also I'm not able to disable 422 validation error ,how can I remove 422 validation error its coming by default help me with this @tiangolo @Jedore @vanntile @Pluckerpluck @JKearnsl |
Beta Was this translation helpful? Give feedback.
-
I made a decorator and decorate the openapi method in runtime. Please note, I only remove the 422 response if the schema ends with from typing import Callable
def customize_openapi(func: Callable[..., dict]) -> Callable[..., dict]:
"""Customize OpenAPI schema."""
def wrapper(*args, **kwargs) -> dict:
"""Wrapper."""
res = func(*args, **kwargs)
for _, method_item in res.get("paths", {}).items():
for _, param in method_item.items():
responses = param.get("responses")
# remove default 422 - the default 422 schema is HTTPValidationError
if "422" in responses and responses["422"]["content"][
"application/json"
]["schema"]["$ref"].endswith("HTTPValidationError"):
del responses["422"]
return res
return wrapper Usage: # Create the application
app = FastAPI()
app.openapi = customize_openapi(app.openapi) |
Beta Was this translation helpful? Give feedback.
-
Thinking that it should be an option to turn off the default 422 response. @tiangolo What do you think about this? There are cases in an API Request that there will be no scenario that returns a 422 response if your route controller is correctly setup. What others say? |
Beta Was this translation helpful? Give feedback.
-
I don't want to initialize the Just call the app_ = FastAPI()
for _, method_item in app_.openapi().get("paths").items():
for _, param in method_item.items():
responses = param.get("responses")
if "422" in responses:
del responses["422"] |
Beta Was this translation helpful? Give feedback.
-
I do appreciate the assistance, thank you. Ill definitely give it a shot thanks for the tip.
…________________________________
From: Ben Pyungwoo Yoo ***@***.***>
Sent: Wednesday, February 7, 2024 7:17 PM
To: tiangolo/fastapi ***@***.***>
Cc: Subscribed ***@***.***>
Subject: Re: [tiangolo/fastapi] How to disable the default 422 doc (Discussion #6695)
I don't want to initialize the openapi_schema myself.
Here is a better way.
app_ = FastAPI()
for _, method_item in app_.openapi().get("paths").items():
for _, param in method_item.items():
responses = param.get("responses")
if "422" in responses:
del responses["422"]
—
Reply to this email directly, view it on GitHub<#6695 (comment)>, or unsubscribe<https://github.com/notifications/unsubscribe-auth/BE7DINDNTFQLWXOFLVRHJADYSQRSVAVCNFSM6AAAAAA2HMZC5SVHI2DSMVQWIX3LMV43SRDJONRXK43TNFXW4Q3PNVWWK3TUHM4DIMBRG4YDG>.
You are receiving this because you are subscribed to this thread.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
My newest solution: