Change pydantic default error message in fastapi? #9420
-
First Check
Commit to Help
Example Codeimport uvicorn
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/")
async def read_items(name:str= Query(max_length=5,error_message='name too long'),
age:int= Query(error_message='age need intger')):
return '...'
if __name__ == '__main__':
uvicorn.run(app="main:app", host="localhost", port=5000)DescriptionI type:http://localhost:5000/?name=asdfasdfasdfasdreerer&age=s and the error message is below: I want to show my own error message 'error message' is a assumed property Operating SystemWindows Operating System DetailsNo response FastAPI Version0.95.0 Python Version3.10.9 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
|
Your question is not quite clear however one way to do this is to use pythons gettext module and use the |
Beta Was this translation helpful? Give feedback.
-
|
You could change the |
Beta Was this translation helpful? Give feedback.
-
|
I don't think such feature would ever been implemented - it seems not good to me to specify one error message for all possible errors for this parameter. But you can implement such logic using the following approach: from fastapi import FastAPI, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI()
def format_error_msg(err: dict):
if err["type"] == "string_too_long":
err["msg"] = f"{err['loc'][-1]} too long"
if err["type"] == "int_parsing":
err["msg"] = f"{err['loc'][-1]} need integer"
return err
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = [format_error_msg(err) for err in exc.errors()]
return JSONResponse(
status_code=422,
content={"detail": errors},
)
@app.get("/")
async def read_items(
name: str = Query(max_length=5),
age: int = Query(),
):
return "..." |
Beta Was this translation helpful? Give feedback.
I don't think such feature would ever been implemented - it seems not good to me to specify one error message for all possible errors for this parameter.
But you can implement such logic using the following approach: