mercredi 15 décembre 2021

REST service design with DTOs, composition and schema validation

For some time I am trying to figure out most suitable pattern(s) to use with REST services and with regards to composite objects, DTO and schema validation.

Consider trivial pseudo code:

class UserDto:
  id: primary key, auto inc, unique
  salutation: string, can be null
  email: string, unique

class PhoneDto:
  id: primary key, auto inc, unique
  number: string
  user_id: foreign key pointing to a user record

Each user object can have zero or more phone records attached to it.

Say we are developing CRUD methods for User:

  1. When creating user, id should not be passed at all, since it will be assigned by the DB. In all other cases, id is mandatory:
  2. when deleting user object, we pass the id and return deleted object to the caller (all fields from user table, but not from the phones table).
  3. When updating, id is again mandatory, but all other fields are optional: caller maybe wants to set salutation since forgot earlier, or wants to change email. Either way this call makes sense with id set and at least one parameter to be altered. Finally,
  4. reading also needs user id but also optionally to load assigned phones.

Now, the question(s):

  1. Shall DTO objects in general be separated/decoupled from business model? Since mainly ORMs specifics reside in DTOs, looks like logical move to decouple, but would like to here opinions on this and what are some recommendations regarding which pattern to use, etc.
  2. When creating an user object, shall we send nested address-es in the same call or is it recommended to make second call and send list of addresses to appropriate endpoint. For more complex cases, like user is having a profile or some other tables related, number of additional calls raises accordingly, but still, maybe the code will remain cleaner if we do this instead making composite payloads at the expense of more traffic (assume objects are not huge blobs of data)
  3. Now, how 1. and 2. are affecting usage of Swagger? I would like to cover endpoints with nice Swagger but not sure how complicated it would be
  4. What pattern(s) are recommended to use to achieve first 3? Swagger is optional, but it really would be nice to have it. Decorator is the first to come to my mind

I don't target any specific framework so I made the questions as generic as I could. But for the sake of complete information, my main candidate is oat++.

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire