JSON Serialization
JSON serialization is the process of converting Python data into JSON.
What works out of the box
JSON supports:
- strings
- numbers
- booleans
- null
- arrays
- objects
In Python terms:
- str, int, float, bool, None
- list/tuple
- dict
What does NOT serialize automatically
Common non-serializable types:
datetimedatetime- database model objects
- Decimal
You must convert them.
Serialization strategies
1) Manual dict conversion
user_dict = {"id": user.id, "username": user.username}
return user_dictuser_dict = {"id": user.id, "username": user.username}
return user_dict2) Helper method on model
class User(db.Model):
# ...
def to_dict(self):
return {"id": self.id, "username": self.username}class User(db.Model):
# ...
def to_dict(self):
return {"id": self.id, "username": self.username}3) Schema libraries (later)
For larger APIs, people use:
- Marshmallow
- Pydantic
This tutorial track keeps it simple: manual to_dict()to_dict() is fine.
Error response shape (recommended)
Try to keep error responses consistent:
{ "error": "validation_error", "message": "Email is required" }{ "error": "validation_error", "message": "Email is required" }Consistency makes frontend/mobile clients much easier to build.
๐งช Try It Yourself
Exercise 1 โ Create a Flask App
Exercise 2 โ Dynamic Route
Exercise 3 โ Return JSON
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
