Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork8.3k
-
First Check
Commit to Help
Example Code#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.12"# dependencies = [# "fastapi==0.118.3",# "pydantic>=2.9.0",# ]# ///importjsonimporttypingfromfastapiimportFastAPIfrompydanticimportBaseModel# Model using typing.Self for recursive structureclassNode(BaseModel):id:strchildren:list[typing.Self]# FastAPI applicationapp=FastAPI()@app.get("/node",response_model=Node)defget_node():"""Get a node with children."""returnNode(id="root",children=[Node(id="child1",children=[]),Node(id="child2",children=[]) ] )if__name__=="__main__":try:pydantic_schema=Node.model_json_schema()print(json.dumps(pydantic_schema,indent=2))exceptExceptionase:print(f"✗ Pydantic failed:{e}")openapi_schema=app.openapi()print(json.dumps(openapi_schema,indent=2)) DescriptionGenerating the OpenAPI specification with a model that uses a field with This used to work, in FastAPI 0.118.x . This broke in 0.119 (and still broken in 0.121.1), where pydantic v1 compat code was introduced. Generating the JSON schema using pydantic words, but not when it gets called through the fastAPI compat code. Not that hard to workaround, by specifying the exact type or using generics, but we loose the nice subclass-ability and readability of Self. Operating SystemLinux Operating System DetailsNo response FastAPI Version2.12.4 Pydantic Version0.121.0 Python VersionPython 3.14.0 Additional ContextRun the example code with FastAPI 0.118.3 and you get a working OpenAPI spec. |
BetaWas this translation helpful?Give feedback.