Skip to main content

Serializing and Deserializing Data Models

Converting Objects to Dictionaries (to_dict)

The to_dict() method on Bookmark, Collection, and Tag objects allows you to serialize an instance into a dictionary. This is particularly useful for preparing data to be sent as JSON in API responses.

Bookmark Example

To convert a Bookmark object to a dictionary, simply call its to_dict() method. This method handles the conversion of special types like datetime objects (typically to ISO 8601 strings) and BookmarkStatus enums (to their string values).

from datetime import datetime
from enum import Enum

class BookmarkStatus(Enum):
UNREAD = "unread"
READ = "read"
ARCHIVED = "archived"

class Bookmark:
def __init__(self, id, url, title, status, created_at):
self.id = id
self.url = url
self.title = title
self.status = status
self.created_at = created_at

def to_dict(self):
return {
"id": self.id,
"url": self.url,
"title": self.title,
"status": self.status.value, # Convert enum to string
"created_at": self.created_at.isoformat() # Convert datetime to ISO string
}

# Example Usage
bookmark = Bookmark(
id="b123",
url="https://example.com/article",
title="An Interesting Article",
status=BookmarkStatus.UNREAD,
created_at=datetime.now()
)

bookmark_dict = bookmark.to_dict()
print(bookmark_dict)
# Expected output (id, created_at will vary):
# {
# 'id': 'b123',
# 'url': 'https://example.com/article',
# 'title': 'An Interesting Article',
# 'status': 'unread',
# 'created_at': '2023-10-27T10:00:00.123456'
# }

Collection Example

Similarly, a Collection object can be converted to a dictionary using to_dict(). This method will handle the serialization of the CollectionType enum.

from enum import Enum

class CollectionType(Enum):
MANUAL = "manual"
SMART = "smart"

class Collection:
def __init__(self, id, name, type):
self.id = id
self.name = name
self.type = type

def to_dict(self):
return {
"id": self.id,
"name": self.name,
"type": self.type.value # Convert enum to string
}

# Example Usage
collection = Collection(
id="c456",
name="My Reading List",
type=CollectionType.MANUAL
)

collection_dict = collection.to_dict()
print(collection_dict)
# Expected output:
# {
# 'id': 'c456',
# 'name': 'My Reading List',
# 'type': 'manual'
# }

Tag Example

The Tag object also provides a to_dict() method to convert its attributes, including the TagColor enum, into a dictionary.

from enum import Enum

class TagColor(Enum):
RED = "red"
BLUE = "blue"
GREEN = "green"

class Tag:
def __init__(self, id, name, color):
self.id = id
self.name = name
self.color = color

def to_dict(self):
return {
"id": self.id,
"name": self.name,
"color": self.color.value # Convert enum to string
}

# Example Usage
tag = Tag(
id="t789",
name="Python",
color=TagColor.BLUE
)

tag_dict = tag.to_dict()
print(tag_dict)
# Expected output:
# {
# 'id': 't789',
# 'name': 'Python',
# 'color': 'blue'
# }

Creating Objects from Dictionaries (from_dict)

The from_dict() static method (or class method) on Bookmark, Collection, and Tag classes allows you to deserialize a dictionary back into an object instance. This is essential when parsing incoming JSON data from API requests.

Bookmark Example

To create a Bookmark object from a dictionary, pass the dictionary to the Bookmark.from_dict() method. This method is responsible for converting dictionary values back into their appropriate types, such as parsing ISO 8601 strings into datetime objects and string values into BookmarkStatus enums.

from datetime import datetime
from enum import Enum

class BookmarkStatus(Enum):
UNREAD = "unread"
READ = "read"
ARCHIVED = "archived"

class Bookmark:
def __init__(self, id, url, title, status, created_at):
self.id = id
self.url = url
self.title = title
self.status = status
self.created_at = created_at

@classmethod
def from_dict(cls, data):
return cls(
id=data["id"],
url=data["url"],
title=data["title"],
status=BookmarkStatus(data["status"]), # Convert string to enum
created_at=datetime.fromisoformat(data["created_at"]) # Convert ISO string to datetime
)

# Example Usage
bookmark_dict = {
'id': 'b123',
'url': 'https://example.com/article',
'title': 'An Interesting Article',
'status': 'unread',
'created_at': '2023-10-27T10:00:00.123456'
}

bookmark_obj = Bookmark.from_dict(bookmark_dict)
print(bookmark_obj.id)
print(bookmark_obj.status)
print(bookmark_obj.created_at)
# Expected output:
# b123
# BookmarkStatus.UNREAD
# 2023-10-27 10:00:00.123456

Collection Example

The Collection.from_dict() method takes a dictionary and constructs a Collection object, correctly converting the string representation of CollectionType back into its enum member.

from enum import Enum

class CollectionType(Enum):
MANUAL = "manual"
SMART = "smart"

class Collection:
def __init__(self, id, name, type):
self.id = id
self.name = name
self.type = type

@classmethod
def from_dict(cls, data):
return cls(
id=data["id"],
name=data["name"],
type=CollectionType(data["type"]) # Convert string to enum
)

# Example Usage
collection_dict = {
'id': 'c456',
'name': 'My Reading List',
'type': 'manual'
}

collection_obj = Collection.from_dict(collection_dict)
print(collection_obj.id)
print(collection_obj.type)
# Expected output:
# c456
# CollectionType.MANUAL

Tag Example

To create a Tag object from a dictionary, use the Tag.from_dict() method. This method handles the conversion of the color string back into a TagColor enum.

from enum import Enum

class TagColor(Enum):
RED = "red"
BLUE = "blue"
GREEN = "green"

class Tag:
def __init__(self, id, name, color):
self.id = id
self.name = name
self.color = color

@classmethod
def from_dict(cls, data):
return cls(
id=data["id"],
name=data["name"],
color=TagColor(data["color"]) # Convert string to enum
)

# Example Usage
tag_dict = {
'id': 't789',
'name': 'Python',
'color': 'blue'
}

tag_obj = Tag.from_dict(tag_dict)
print(tag_obj.id)
print(tag_obj.color)
# Expected output:
# t789
# TagColor.BLUE

Handling Special Data Types

When serializing and deserializing, special attention is paid to certain data types to ensure they are correctly represented in dictionaries and then reconstructed into Python objects.

Datetime Objects

datetime objects, such as created_at in the Bookmark model, are typically converted to and from ISO 8601 formatted strings (YYYY-MM-DDTHH:MM:SS.ffffff) for serialization.

  • to_dict(): Uses datetime_obj.isoformat() to convert a datetime object into a string.
  • from_dict(): Uses datetime.fromisoformat(string_value) to parse an ISO 8601 string back into a datetime object.

Enum Types

Enum types like BookmarkStatus, CollectionType, and TagColor are converted to their string value when serializing and reconstructed from their string value when deserializing.

  • to_dict(): Accesses the value attribute of the enum member (e.g., BookmarkStatus.UNREAD.value which yields "unread").
  • from_dict(): Passes the string value directly to the Enum class constructor (e.g., BookmarkStatus("unread") which yields BookmarkStatus.UNREAD). This requires the string value to exactly match one of the enum's defined values.