Following the Pydantic custom data types instructions, I've created a type which attempts to get strings from a single comma-separated string like:
"foo,bar,baz" -> ["foo", "bar", "baz"]
It works fine:
class CommaSeparatedString(str):
@classmethod
def __get_validators__(cls):
yield cls.split_on_comma
@classmethod
def split_on_comma(cls, v: str | None):
if not v:
return None
if not isinstance(v, str):
raise TypeError("String required")
return [item.strip() for item in v.split(",")]
@app.get("/")
def applications_index(
strings: CommaSeparatedString | None,
):
print(strings)
But FastAPI doesn't honour the optional nature of the strings
param.
It complains about missing fields when I make a request without strings
in the querystring:
{'detail': [{'loc': ['query', 'strings'], 'msg': 'field required', 'type': 'value_error.missing'}]