» Python: Building Event-Driven Microservices with Kafka » 2. Producer: Web Service » 2.3 Data Models

Data Models

Data models represent the structure of the data that the API deals with. These models define the shape of the data entities exchanged between the client and the server.

For example, in this books management microservices project, a Book model can be defined:

Create domain/model/book.py:

Folder structures like domain/model/... is using 4 Layers Architecture Pattern, read more here.

from dataclasses import dataclass
from datetime import datetime

@dataclass
class Book:
    id: int
    title: str
    author: str
    published_at: str
    description: str
    created_at: datetime

Create domain/model/__init__.py:

from .book import Book

Tip:
The __init__.py file serves two main purposes in Python:

  1. Package Initialization: When Python imports a directory that contains an __init__.py file, it treats it as a package. The __init__.py file is executed upon import of the package and can be used to perform package initialization tasks.
  2. Symbol Exporting: It controls what symbols (functions, classes, variables) are available for import from the package. By importing modules or symbols into __init__.py, you can make them available for import directly from the package itself.
PrevNext