How to properly achieve different example(s) for same type/model per endpoint? #11170
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Path
from typing import Annotated
from copy import deepcopy
app = FastAPI()
item_id_type = Annotated[str, Path(description='This is my Item ID', ge=10, le=50, example=12)]
item_id_type_b = deepcopy(item_id_type)
item_id_type_b.__metadata__[0].example = 17
@app.get('/route_a')
def operation_a(item_id: item_id_type) -> str
if item_id == 17:
raise ValueError('item with id 17 doesnt support this operation')
return f'id: {item_id}'
@app.get('/route_a')
def operation_b(item_id: item_id_type_b) -> str:
if item_id == 12:
raise ValueError('item with id 12 doesnt support this operation')
return f'id: {item_id}DescriptionI'm trying to have a single type that represents an item ID but make different endpoints use a different example. rightnow I'm using a workaround by copying the original type and then mutate the example like so: item_id_type_b = deepcopy(item_id_type)
item_id_type_b.__metadata__[0].example = 17Is there a better way to have a single type/model with its validations etc but use different examples per endpoint? Everything else i tied either didn't work or overrides the Path-definition entirely. Operating SystemOther Operating System DetailsWSL (ubuntu) on Windows 10 FastAPI Version0.109.2 Pydantic Version2.5.3 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
This seems to be working: BTW, |
Beta Was this translation helpful? Give feedback.
This seems to be working:
BTW,
geandleare not working forstr…