Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

386
Views
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
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!