Some of the important concept on Fast API are covered on this blog.
Which are useful in different scenario while doing the FastAPI Projects.
# pip install fastapi pydantic pydantic[email]
from pydantic import BaseModel,Field,EmailStr
from datetime import datetime,timezone
from fastapi.encoders import jsonable_encoder
class User(BaseModel):
name: str = Field(..., alias="username")
email:EmailStr
age:int
created_time: datetime | None = datetime.now(timezone.utc)
read_time: datetime | None = None
active:bool=True
1.jsonable_encoder(...)
— from FastAPI / Pydantic Utils
jsonable_encoder
is a utility function (from FastAPI, not directly Pydantic) that:
Converts any Python object (like a Pydantic model, datetime
, UUID
, Decimal
, etc.) into a JSON-compatible format — ready to be sent in a JSON response or stored as JSON.
Why use jsonable_encoder
?
Because Python data types like datetime
, UUID
, etc., are not JSON serializable by default.
from fastapi.encoders import jsonable_encoder
from datetime import datetime
jsonable_encoder({"time": datetime.utcnow()})
# Output: {"time": "2025-05-05T12:34:56.789Z"}
# it will convert the datetime object into jsonable string
If you try to directly use json.dumps()
without this encoder, it will raise a TypeError
.
user=User(username="panta",email="[email protected]",age=25,active=False)
print(jsonable_encoder(user))
# it will convert complex data type (pydantic model into jsonable)
Output:
{'username': 'panta', 'email': '[email protected]', 'age': 25, 'created_time': '2025-05-05T07:02:11.523594Z', 'read_time': None, 'active': False}
2.skip_defaults=True
(deprecated in Pydantic v2)
This flag is used when initializing a Pydantic model to tell it:
Don't include fields that have default values unless explicitly passed.
skip_defaults=True
was previously used with .dict(skip_defaults=True)
in Pydantic v1 — now deprecated in Pydantic v2.
So what should be done?
If you want to exclude default values when serializing, use:
In Pydantic v1:
user.dict(skip_defaults=True)
In Pydantic v2
user.model_dump(exclude_defaults=True)
user=User(username="panta",email="[email protected]",age=25,active=False)
print(user.model_dump(exclude_defaults=True))
# print(type(user.model_dump())) #dict
# print(type(user.model_dump_json())) #str
Output:
{'name': 'panta', 'email': '[email protected]', 'age': 25, 'active': False}