What we will cover? (Recap)
- Generic validations and metadata:
- alias -> Show as placeholder
- title -> Show as title
- description -> show as params description
- deprecated (ডেফরিকেটেট) -> make disable
- Strings Validations:
- min_length -> set min length of string
- max_length -> set max length of string
- pattern -> regular ex
@app.get("/items", tags=["get items"])
async def get_items(q: str | None = None):
# async def get_items(q: Annotated[str] = None):
results: dict[str, list[dict[str, str]]] = {
"items": [
{"item_id": "Foo"},
{"item_id": "Bar"}
]
}
if q:
results.update({"query": q})
return results
- query Length validation
- We can use 2 way our query validations (Without
Annotated
)
q: str | None = None
- With
Annotated
q: Annotated[str | None] = None
- With Query
fastapi
method
q: Annotated[str | None, Query(max_length=10)] = None
- Note: Both of those versions mean the same thing
- We can use 2 way our query validations (Without
- We can also add min_length for validation
q: Annotated[str | None, Query(min_length=3, max_length=50)] = None
We can also define a regular expression pattern that the parameter should match. We can also call this parameter parttern
Query(min_length=3, max_length=50, pattern="^sabbir$")
^
: starts with the following characters, doesn't have characters before.
sabbir
: has the exact value sabbir.
$
: ends there, doesn't have any more characters after sabbir.
query: Annotated[list[str] | None, Query()] = None