Skip to content
Discussion options

You must be logged in to vote

You can use WrapValidator for this reason:

from typing import Annotated, Any
from fastapi import FastAPI, Query
from pydantic import ValidationError, ValidatorFunctionWrapHandler, WrapValidator


app = FastAPI()


def override_err(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
    try:
        return handler(value)
    except ValidationError:
        raise ValueError("CUSTOM MESSAGE")


@app.get("/items/")
async def read_items(
    filter_query: Annotated[
        str, Query(min_length=10, max_length=100), WrapValidator(override_err)
    ],
):
    return filter_query

Or, configurable version:

from typing import Annotated, Any
from fastapi import FastAPI, Query
from pydantic im…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
2 replies
@YuexiaW
Comment options

@Kfir-G
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
4 participants