Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Documenting multiple possible return types in Swagger

Please consider the following method:

[HttpGet("abc")]
public List<BaseClass> GetThemAll()

There are 3 types that derive from BaseClass. I would like to provide documentation for the 3 available types.

Q: Is it possible to provide documentation for these 3 derived types (using NSwag)?

So far I've tried using <see but the Models section of Swagger UI does not contain the subtypes.

/// <returns>(...) Returned types are: <see cref="TypeA"/>, <see cref="TypeB"/> or <see cref="TypeC"/></returns>    
like image 321
tymtam Avatar asked Sep 20 '25 09:09

tymtam


1 Answers

Its look like you can describe all derived types via KnownType, like:

[KnownType(typeof(DerivedClass1))]
[KnownType(typeof(DerivedClass2))]
[KnownType(typeof(DerivedClass3))]
public class BaseClass { }

Also for visualize inheritance its possible to write own SchemaProcessor. For example:

  [KnownType(typeof(A))]
  [KnownType(typeof(B))]
  public class BaseType
  {
    public int Id { get; set; }
  }

  public class A : BaseType
  {
    public string Name { get; set; }
  }

  public class B : BaseType
  {
    public long A { get; set; }
  }
[HttpGet("abc")]
public List<BaseType> GetThemAll()
  public class InheritanceSchemaProcessor : ISchemaProcessor
  {
    public void Process(SchemaProcessorContext context)
    {
      if (context.Type.Name is nameof(BaseType))
      {
        var attributes = context.Type.GetCustomAttributes(typeof(KnownTypeAttribute), true) as Attribute[];
        foreach (Attribute attribute in attributes)
        {
          var knownTypeAttribute = (KnownTypeAttribute) attribute;
          var schema =
            context.Generator.GenerateWithReference<JsonSchema>(knownTypeAttribute.Type.ToContextualType(), context.Resolver);
          context.Schema.AnyOf.Add(schema);
        }
        
        context.Schema.Properties.Clear();
        context.Schema.AllowAdditionalProperties = true;
      }
    }
  }

and in Startup.cs in ConfigureServices:

      services.AddOpenApiDocument(s =>
      {
        s.SchemaType = SchemaType.OpenApi3;
        s.SchemaProcessors.Add(new InheritanceSchemaProcessor());
        s.FlattenInheritanceHierarchy = true;
      });

Result

like image 95
Anton Komyshan Avatar answered Sep 22 '25 23:09

Anton Komyshan