Search code examples
api-design

What is the best way to handle different Web API classes


This question keeps popping out every time I create a new Solution.

I would like to separate the Request Object, Database Entity and Response Object. If your Web API handles few entities I agree that it is not necessary to separate them. But what if I have the following requirements:

  1. Request Objects (api payload) has:

    • FirstName
    • LastName
    • BirthDate
  2. Database Entities (table) has:

    • Id
    • FirstName
    • LastName
    • BirthDate
    • CreateDate (for audit)
    • CreateBy (for audit)
    • UpdateDate (for audit)
    • UpdateBy (for audit)
  3. Response Objects (api body) has:

    • Id
    • FirstName
    • LastName
    • BirthDate
    • Age (calculated, readonly)

(Questions) > so with this idea in mind:

  1. Does it make sense to create separate classes for each type of objects?
  2. What naming convention can i use?
  3. Is there already a best practice to handle this different kind of objects?
  4. Is it fine to just use the suffixes Request, Entity, Response for each type of objects?

Reply are greatly appreciated!


Solution

  • 1 - Does it make sense to create separate classes for each type of objects? No. You can use one model and different mappers, it's make more sense than handle with different models about the same subject

    2 - What naming convention can i use? It's depends on the name's convention your company is using.

    3 - Is there already a best practice to handle this different kind of objects? Yes, you can use mapper pattern to map each different input/output: Repository and Data Mapper pattern

    Also, this article can help with a good architectural standard: https://www.infoq.com/articles/advanced-architecture-aspnet-core/

    4 - Is it fine to just use the suffixes Request, Entity, Response for each type of objects? It is depends on the name's convention again, but it is possible.