How does schema reuse work in OpenAPI (via $ref and components/schemas), and how does Swashbuckle handle types shared across multiple endpoints?
Short answer
OpenAPI's components/schemas section defines reusable type definitions once, referenced elsewhere via $ref pointers instead of duplicating the full schema inline at every usage -- Swashbuckle automatically deduplicates C# types used across multiple endpoints into this shared…
Advertisement
AModel answer
OpenAPI's components/schemas section defines reusable type definitions once, referenced elsewhere via $ref pointers instead of duplicating the full schema inline at every usage -- Swashbuckle automatically deduplicates C# types used across multiple endpoints into this shared schemas section (using the type name as the schema key), which is why giving DTOs clear, unique names matters, since naming collisions between different types with the same short name can cause schema generation conflicts.
// Both endpoints reference the same ProductDto schema via $ref
// rather than duplicating its full definition twice in the OpenAPI document
[HttpGet("{id}")]
public ActionResult<ProductDto> GetProduct(int id) { ... }
[HttpPost]
public ActionResult<ProductDto> CreateProduct(ProductDto dto) { ... }
// Swashbuckle generates ONE #/components/schemas/ProductDto, referenced by both operationsReal-world example
A team encounters a Swashbuckle schema ID conflict error after two unrelated features both defined a class named 'Response' in different namespaces, requiring a custom SchemaId resolver to disambiguate them in the generated document.
Likely follow-ups
- How do you resolve a schema naming conflict using a custom SchemaId function?
- What's the benefit of $ref-based reuse for very large APIs with hundreds of endpoints?
Related topics