3

I'm designing a Web API and I've enabled Swagger on it.

My Create and Update operations share the same entity. I'm not using DTOs, but the actual Model.

class Person 
{
     public int Id { get; set; }
     public string Name {  get; set }
}

The problem is that doing this way, the Create operation is confusing to the consumers of the API, because Swagger states that accepts an Id, while it should not. In fact, it should be shown in the Sample data.

Is there a good an easy way to avoid using DTOs (I hate mapping) while keeping the API free of this confusion?

SuperJMN
  • 13,110
  • 16
  • 86
  • 185
  • No, not really. While you can use a document/schema filter to remove the property from the schema definition, it will remove it everywhere, including on the model definitions on the get methods. Maybe you could duplicate the schemas in one of the filters (i.e. duplicate it and rename it `CreatePerson` and assign it to the path definition, but that'd probably be way more work. Using entities as Api model is bad anyways, especially if you use ORM like EF or EF Core – Tseng Sep 06 '17 at 16:12
  • Or you could replace the swagger references with inline models... but that's kinda ugly, will blow up the size of your swagger.json and probably cause issues with swagger code generators such as `swagger-codegen` or `autorest`. So no real elegant solutions. Cleanest is the DTO (I rather call them contracts when it comes to rest), then you won't break your rest service, when you change your db layout/entities – Tseng Sep 06 '17 at 16:20
  • Thanks for the answer, but why using a Model instead of DTO is bad? I'm a bit lost because I've been told the opposite a few hours ago, by a lot of members in the community that state that using DTO is harmful because it a big source of duplication / with tedious mapping. Please, check this question: https://stackoverflow.com/questions/46073058/should-i-have-different-dtos-for-create-and-update-crud/46073503?noredirect=1#comment79116640_46073503 – SuperJMN Sep 06 '17 at 19:50
  • 1
    See my previous comment. Every change to your entity, will break the rest api contract and every application which uses your rest service. You can't version it. When using EF Core, you will have navigation properties there which may even cause circular dependency (Customer having Navigation Property to Order and order having navigation property to customer, trying to serialize this will result in exception or seemingly "unreferenced" navigation property (if JSON.NET is set to stop when it detects a circular reference – Tseng Sep 06 '17 at 19:54
  • For example if A references B, and B references a list of A'. Now if B references 10 different A entities and you request A(id=1), then the B will contain 9 references when serialized to json (9 which are referenced by it, but A(id=1) will be excluded to avoid self-reference). It's just not worth the trouble. – Tseng Sep 06 '17 at 19:59

0 Answers0