Replies: 7 comments
-
|
You could try declaring a from typing import Type, TypeVar
from fastapi import APIRouter, Depends
from pydantic import BaseModel
router = APIRouter()
T = TypeVar("T", bound=BaseModel)
class ExampleModel(BaseModel):
example: str
class ExampleClass:
# BaseModel just for editor suggestions, model will always be a class
# inherited from BaseModel, A.K.A a pydantic model
def __init__(self, model: Type[T]) -> None:
self.model = model
async def __call__(self, input: Type[T]):
return (
"Hello, this is an example. An 422 should be raised if input "
"doesn't match the model"
)
example_dependency = ExampleClass(ExampleModel)
@router.post("/")
async def example_endpoint(payload=Depends(example_dependency)):
return payload |
Beta Was this translation helpful? Give feedback.
-
|
Hey @uolot! Thanks for answering. I have some doubts, maybe because I'm not used to work with TypeVar. |
Beta Was this translation helpful? Give feedback.
-
|
That's exactly what a
In the example code I posted I get use the type of the generic type, which means this calls will pass mypy checks:
If you want to pass an instance of
|
Beta Was this translation helpful? Give feedback.
-
|
Thanks @uolot! I don't exactly understand why, but input is only being checked if I use Although, if I name the parameter of my {
"detail": [
{
"loc": [
"query",
"input"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}Nevertheless, if I use |
Beta Was this translation helpful? Give feedback.
-
|
To get the validation working you need to either declare the Regarding your second issue, it would be helpful if you provide more code and show how exactly you call that endpoint. |
Beta Was this translation helpful? Give feedback.
-
Using this code, call {
"example": "value"
}and you will get a 422 response with the following message: {
"detail": [
{
"loc": [
"query",
"input"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}which is asking for a query parameter called input. This is due to the way FastAPI recognises parameters, which according to the docs is:
Since |
Beta Was this translation helpful? Give feedback.
-
|
Closing this issue because a new one has been opened to discuss the specific topic. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First check
Example
Here's a self-contained, minimal, reproducible, example with my use case:
Description
My question is in file dependencies.py at call method, I cannot use self.model as a type hint because self is not defined yet, but I want this method to automatically return the 422 FastAPI returns when a model is not matched.
The reason why I'm not directly using the ExampleModel itself is that I want ExampleClass to be independent of the input, so I can reuse it as a dependency for multiple methods.
Environment
Beta Was this translation helpful? Give feedback.
All reactions