'How to pass typedDict as arguments in python for fastapi

I am working in this simple fastapi example, I would like to replace the read_books arguments with a equivalent TypedDict, like the commented line. Is it possible?

from fastapi import FastAPI, Query
from typing import Optional, TypedDict


# would like to define model for query parameter in separeted object
class GetModel(TypedDict):
    test: Optional[str]


query_param =  GetModel(test=Query('default value', max_length=10, title='titulo', description="description 123", regex="^[a-z]+"))



app = FastAPI()

@app.get("/books")
def read_books(test: Optional[str] = Query('default value', max_length=10, title='titulo', description="description 123", regex="^[a-z]+")):
#def read_books(query_param):
    """
    comentario do endpoint
    """
    results = {"books": [{"book_name": "The Great Hunt"}, {"book_name": "The Dragon Reborn"}]}

    if test:
        results.update({"test": {"name":test}})
    
    return results


Solution 1:[1]

The way to do this is to implement your query parameter parsing in a separate class dependency, as described in the documentation (also, have a look at this discussion). Example below:

from fastapi import FastAPI, Query, Depends
from typing import Optional

app = FastAPI()

class MyModel:
    def __init__(
        self,
        test: Optional[str] = Query('default value', max_length=10, title='titulo', description="description 123", regex="^[a-z]+")
    ):
        self.test = test


@app.get("/books")
def read_books(m: MyModel = Depends(MyModel)):
    results = {"books": [{"book_name": "The Great Hunt"}, {"book_name": "The Dragon Reborn"}]}
    if m.test:
        results.update({"test": {"name": m.test}})
    return results

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1