{
  "$type": "site.standard.document",
  "canonicalUrl": "https://johnnyreilly.com/posts/swashbuckle-schemaid-already-used",
  "description": "Swashbuckle can fail to generate a swagger / Open API document with the message \"The same schemaId is already used...\". This post offers a way forward.",
  "path": "/posts/swashbuckle-schemaid-already-used",
  "publishedAt": "2022-08-31T00:00:00.000Z",
  "site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
  "tags": [
    "swagger"
  ],
  "textContent": "Swashbuckle can fail to generate a swagger / Open API document with the message \"The same schemaId is already used...\". This post explains what that means, and offers a way to work around it.\n\n\n\n\"The same schemaId is already used...\"\n\nWhen creating a swagger / Open API document with Swashbuckle, it's possible to encounter an error of this nature:\n\nRichard Morris explains the reason for this here:\n\n> By default, SB uses the short (unqualified name) which has its benefits because it keeps the docs simpler but also it’s downside if model names are duplicated in different namespaces.\n\nThe solution for this is using the CustomSchemaIds configuration option for Swashbuckle. This allows the customisation of type names, such that collisions are prevented. We need types to be unique strings. A simple way to tackle this is something like this:\n\nHowever, the types created using the above approach can be verbose. Wouldn't it be nice if we could essentially have the names we had before, but just handle duplicates with an incrementing number?\n\nNicer names with SwashbuckleSchemaHelper\n\nWe can do exactly this. What we'll do is put together a class called SwashbuckleSchemaHelper:\n\nThe above class borrows the DefaultSchemaIdSelector implementation from Swashbuckle itself. It creates the type name using that, and then uses a Dictionary to track the numbers of usages of it; suffixing a number where there are duplicates to indicate which duplicate is in play on this occasion. This number suffix is inspired by an answer on Stack Overflow and also by Glenn Piper's comment here.\n\nUsage of this looks like this:\n\nThe result of using this approach is that you'll start to generate multiple types: MyType and MyType2, and importantly a goodbye to the \"The same schemaId is already used...\" message.",
  "title": "Swashbuckle and schemaId is already used"
}