Interview frequency: …
Short answer
Define request and response models specific to the API (DTOs) for validation and serialization, and convert them to independent internal domain models, so the JSON shape and names do not leak into business logic.
Explanation
Coupling the two directly means any API change breaks business logic and exposes internal fields to the outside (such as password_hash or is_admin when receiving data). Separation allows multiple API versions on the same domain, and hiding sensitive fields in the response. Reject unexpected fields if that is part of the security contract (to prevent mass assignment), and return helpful validation messages.
Code example
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, EmailStr
class CreateUserIn(BaseModel): # API schema
model_config = ConfigDict(extra="forbid")
email: EmailStr
display_name: str
@dataclass
class User: # domain model
email: str
name: str
is_admin: bool = False
def to_domain(payload: CreateUserIn) -> User:
return User(email=payload.email.lower(), name=payload.display_name)Common mistakes
- Accepting the database model directly from the request, so a user can modify is_admin.
- Returning the database model in the response, leaking sensitive fields.