Question Details

No question body available.

Tags

python fastapi python-typing pydantic

Answers (2)

April 13, 2026 Score: 3 Rep: 35 Quality: Low Completeness: 50%

Since the concrete type is fixed at startup, the best solution is to resolve the concrete model once and use it as the response model, instead of trying to express it as a generic. This way Fast API is able to properly validate and serialize the response.

Something like:

ItemModel = resolveitemmodelfromenv()  # e.g. AItem, BItem, etc.

@app.get("/items", responsemodel=list[ItemModel]) def getitems(): return getitems()

The resolveitemmodelfromenv() function can simply map your configuration value to the corresponding model class.

April 13, 2026 Score: 0 Rep: 3,418 Quality: Low Completeness: 50%

How are you currently passing the config? Is making it an argument to getitems (rather than using globals and such) an option? If so, you could do something along the lines of:

@app.get(path="items")
def getitems[T: BaseItem](itemtype: type[T]) -> list[T]: ...

It'll change the way you call getitems, but it'll also make Pylance more accurate when comparing your return and config types.