TypedDict does not allow optional keys?

Since Python 3.11, as per PEP 655, what you need is NotRequired: class _trending(TypedDict): allStores: NotRequired[bool] category: str date: str average: List[int] notice that you shouldn’t use Optional in TypedDict, and only use (Not)Required if you want to use TypedDict with Pydantic, you could refer this article

pydantic convert to jsonable dict (not full json string)

Pydantic 1.x (old answer) The current version of pydantic does not support creating jsonable dict straightforwardly. But you can use the following trick: Note: This is a suboptimal solution class Model(BaseModel): the_id: UUID = Field(default_factory=uuid4) print(json.loads(Model().json())) {‘the_id’: ‘4c94e7bc-78fe-48ea-8c3b-83c180437774’} Or more efficiently by means of orjson orjson.loads(Model().json()) Pydantic 2 There is model_dump() method accepting mode parameter. … Read more

Make every field as optional with Pydantic

This method prevents data validation Read this by @Anime Bk: https://stackoverflow.com/a/75011200 Solution with metaclasses I’ve just come up with the following: class AllOptional(pydantic.main.ModelMetaclass): def __new__(cls, name, bases, namespaces, **kwargs): annotations = namespaces.get(‘__annotations__’, {}) for base in bases: annotations.update(base.__annotations__) for field in annotations: if not field.startswith(‘__’): annotations[field] = Optional[annotations[field]] namespaces[‘__annotations__’] = annotations return super().__new__(cls, name, bases, … Read more

Pydantic: Detect if a field value is missing or given as null

Pydantic V1 The pydantic documentation desccribes two options that can be used with the .dict() method of models. exclude_unset: whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary; default False. Prior to v1.0, exclude_unset was known as skip_defaults; use of skip_defaults is now deprecated exclude_defaults: whether … Read more

How to add both file and JSON body in a FastAPI POST request?

As per FastAPI documentation: You can declare multiple Form parameters in a path operation, but you can’t also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using application/x-www-form-urlencoded instead of application/json (when the form includes files, it is encoded as multipart/form-data). This is not a … Read more

How to use a Pydantic model with Form data in FastAPI?

I found a solution that can help us to use Pydantic with FastAPI forms 🙂 My code: class AnyForm(BaseModel): any_param: str any_other_param: int = 1 @classmethod def as_form( cls, any_param: str = Form(…), any_other_param: int = Form(1) ) -> AnyForm: return cls(any_param=any_param, any_other_param=any_other_param) @router.post(”) async def any_view(form_data: AnyForm = Depends(AnyForm.as_form)): … It’s shown in the … Read more

How to add a custom decorator to a FastAPI route?

How can I add any decorators to FastAPI endpoints? As you said, you need to use @functools.wraps(…)–(PyDoc) decorator as, from functools import wraps from fastapi import FastAPI from pydantic import BaseModel class SampleModel(BaseModel): name: str age: int app = FastAPI() def auth_required(func): @wraps(func) async def wrapper(*args, **kwargs): return await func(*args, **kwargs) return wrapper @app.post(“https://stackoverflow.com/”) @auth_required … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)