Bound Typevar does not work as body to accept multiple children types of the same parent #9903
-
First Check
Commit to Help
Example Codefrom typing import TypeVar
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from starlette import status
app = FastAPI()
testclient = TestClient(app)
class Parent(BaseModel):
parentAttribute: str
class Child(Parent):
childAttribute: str
PARENT = TypeVar("PARENT", bound=Parent)
@app.post(
"/",
response_model=PARENT,
status_code=status.HTTP_201_CREATED,
)
def add_parentlike_intance(parent: PARENT):
return parent
child = Child(parentAttribute="parent", childAttribute="child")
postresponse = testclient.post(
url=f"/",
data=child.model_dump_json(),
)
assert postresponse.status_code == 201, postresponse.content
# Traceback (most recent call last):
# File "/home/hendrik/.config/JetBrains/PyCharmCE2023.1/scratches/bug_bound_typevar.py", line 35, in <module>
# assert postresponse.status_code == 200, postresponse.content
# AssertionError: b'{"detail":[{"type":"missing","loc":["query","parent"],"msg":"Field required","input":null,"url":"https://errors.pydantic.dev/2.1.2/v/missing"}]}' DescriptionWhen I want to send in a body that is defined as a typevar this does not work.
Operating SystemLinux Operating System DetailsNo response FastAPI Version0.100.0 Python Version3.10.6 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
YuriiMotov
May 16, 2025
Replies: 1 comment
-
You can't create generic endpoints in FastAPI. FastAPI uses type annotations to generate schema and in case using Use And, in it doesn't work well for |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can't create generic endpoints in FastAPI. FastAPI uses type annotations to generate schema and in case using
TypeVar
it would be impossible to generate schema.Use
Union[Parent, Child]
instead.And, in it doesn't work well for
response_model
. In the openapi schema you will only see the schema forParent
as the response model.