Skip to content

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_dict
user_dict = {"id": user.id, "username": user.username}
return user_dict

2) 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.

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 coffee

Was this page helpful?

Let us know how we did