Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23189

How do I keep a correct API spec when using a ModelSerializer?

$
0
0

I'm using a model serializer to serialize a list as a dictionary (thanks to Plagon). This however leaves me with an incorrect API spec.

How do I ensure the API spec is correct?

from uuid import UUID, uuid4from fastapi import FastAPIfrom pydantic import BaseModel, Field, model_serializerclass Item(BaseModel):    uid: UUID = Field(default_factory=uuid4)    number: int = Field(default_factory=lambda: 4)  # https://xkcd.com/221/class ResponseModel(BaseModel):    items: list[Item]    @model_serializer    def serialize_model(self):        return {str(item.uid): item.model_dump() for item in self.items}app = FastAPI()@app.get("/items/", response_model=ResponseModel)def read_item():    return ResponseModel(items=[Item() for _ in range(2)])
{"openapi": "3.1.0","info": {"title": "FastAPI","version": "0.1.0"  },"paths": {"/items/": {"get": {"summary": "Read Item","operationId": "read_item_items__get","responses": {"200": {"description": "Successful Response","content": {"application/json": {"schema": {"$ref": "#/components/schemas/ResponseModel"                }              }            }          }        }      }    }  },"components": {"schemas": {"Item": {"properties": {"uid": {"type": "string","format": "uuid","title": "Uid"          },"number": {"type": "integer","title": "Number"          }        },"type": "object","title": "Item"      },"ResponseModel": {"properties": {"items": { // <- this is wrong as it doesn't now about items being a dict now."items": {"$ref": "#/components/schemas/Item"            },"type": "array",  "title": "Items"          }        },"type": "object","required": ["items"        ],"title": "ResponseModel"      }    }  }}

Viewing all articles
Browse latest Browse all 23189

Trending Articles