Skip to content

Lesson 6 of 9 · 23m

DTOs, Content Encoding, and Error Contracts Clients Can Depend On

Keep transport representations separate from Fluent models, control JSON encoding details, shape errors consistently, and make PATCH semantics explicit.

Returning Fluent models directly feels efficient until a column rename becomes a client outage or a new internal field leaks to every user. Transport objects are a public contract. Database models are implementation detail. Keep that wall intact.

Response DTOs are deliberate compatibility surfaces

struct ProjectResponse: Content {
    var id: UUID
    var name: String
    var createdAt: Date
    var owner: UserSummary
}

struct UserSummary: Content {
    var id: UUID
    var displayName: String
}

Absent are tenant internals, token hashes, deletion state, billing details, and foreign keys the client does not need. Mapping code looks repetitive because it is the place where compatibility decisions live.

JSON details are contract details

let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

ContentConfiguration.global.use(encoder: encoder, for: .json)
ContentConfiguration.global.use(decoder: decoder, for: .json)

Dates, UUID casing, decimal precision, nulls, and absent keys are not cosmetic. Both sides can emit valid JSON while disagreeing about meaning.

Missing, null, and empty are different

{"displayName": null}
{}
{"displayName": ""}

In PATCH semantics, the first may clear a value, the second usually means no change, and the third may set or reject an empty string. Document the choice and implement it deliberately.

Errors should be machine-readable

{
  "error": {
    "code": "project_name_conflict",
    "message": "A project with that name already exists in this workspace.",
    "requestID": "01JZX8M1S2K6N5VJXK2M4Y4H79"
  }
}

Clients branch on code, not prose. The request ID lets support correlate a report with server logs without exposing stack traces.

Version behavior, not just URLs

Additive optional fields are often compatible. Renaming fields, changing meaning, tightening validation, changing ordering, or changing error codes can break clients even when /v1 stays in the path. Large request bodies are resource input too; define size limits before buffering them.

Field notes

  • Encoding a model directly is mass exposure waiting for the next column.
  • Record JSON fixtures and test them; same-library round trips can hide shared mistakes.
  • Do not paper over missing timestamps with Date() at response time.
  • Keep mapping centralized. Ad hoc dictionaries drift quickly.

Was this lesson helpful?

Sign in to rate