2
import 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)

If I type http://localhost:5000/?name=asdfasdfasdfasdreerer&age=s, the error message would be as shown below:

{"detail":[{"loc":["query","name"],"msg":"ensure this value has at most 5 characters","type":"value_error.any_str.max_length","ctx":{"limit_value":5}},{"loc":["query","age"],"msg":"value is not a valid integer","type":"type_error.integer"}]}

However, I would like to display my own custom error message:

{"detail":[{"loc":["query","name"],"msg":"name too long","type":"value_error.any_str.max_length","ctx":{"limit_value":5}},{"loc":["query","age"],"msg":"age need integer","type":"type_error.integer"}]}

'error message' is a assumed property

Chris
  • 18,724
  • 6
  • 46
  • 80
zhizunbao
  • 69
  • 4
  • Does this answer your question? [How to change the default Pydantic error message using FastAPI?](https://stackoverflow.com/questions/71895606/how-to-change-the-default-pydantic-error-message-using-fastapi) – Chris Apr 22 '23 at 07:20
  • [This answer](https://stackoverflow.com/a/71682274/17865804) most likely offers solutions best suited to your problem, as you seem to be looking to customise the error for a specific route only. Some related answers can also be found [here](https://stackoverflow.com/a/75545471/17865804), as well as [here](https://stackoverflow.com/a/71800464/17865804) and [here](https://stackoverflow.com/a/70954531/17865804) – Chris Apr 22 '23 at 07:50
  • In fact.These answers can work but all not I want. I want something like c# https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0 [Required(ErrorMessage = "wrong message")], It very easy to custom own error message. – zhizunbao Apr 26 '23 at 07:40

0 Answers0