Background
When a consumer interacts with my REST API using POST/PATCH/PUT verbs I do not want to expose an entity that includes an ID field. The reason is that this field should not be modified by the consumer of the API at all.
But, when the consumer retrievs an entity using GET, I want the ID of the entity to be exposed.
Question: How do I achieve this in a nice maintainable way?
Possible Solutions
I've identified two ways of doings this that doesn't include magic and plays well with the autogenerated swagger documentation .
First solution: Create a base class without an identifier and then a subclass that inherits from this and adds an ID field.
Base class:
public class Product
{
public string Name { get; set; }
public string Category { get; set; }
public double Price { get; set; }
public DateTimeOffset DateAdded { get; set; }
}
Subclass:
public class IdentifiedProduct : Product
{
public Guid Id { get; set; }
}
Drawback: In effect, I will double the number of entities in every layer of my API.
Second solution: Add a generic decorator class
Generic decorator:
public class IdentifiedEntity<EntityType> where EntityType : class
{
public Guid Id { get; set; }
public EntityType Entity { get; set; }
}
Result in swagger:
Drawback: Ugly json object
Any better solutions?
Aucun commentaire:
Enregistrer un commentaire