Based on this API definition, my api supports queries like:
GET http://my.api.url/posts?sort=["title","ASC"]&range=[0, 24]&filter={"q":"bar"}
where some of the checks needed are
sort[1]is either"asc"or"desc"(case should not matter)filterhas the key"q".filtercan have other keys.rangeis a list of two integers.range[0]is less then or equal torange[1]
In fastapi path definitions I currently define filter, sort, and range as strings as in the code below, convert them using json.loads, and do checks.
@r.get(
"/users",
response_model=List[User],
response_model_exclude_none=True,
)
async def list_users(
filter: Optional[str] = None,
sort: Optional[str] = None,
range: Optional[str] = None,
...
):
...
How can I use pydantic definitions for checks and API definition instead of just using str, such that checks are done by pydantic, and openapi schema definitions are more descriptive?
Dependsto depend on a utilty function that receives a string, decodes the JSON and useparse_objorparse_obj_as(depending on the root level structure of the request JSON) helper function from Pydantic to validate the submitted content against your basemodel.