Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swashbuckle how to add OneOf declaration to OpenAPI 3

I have a request object that can be of 2 string types "A" or "B".

Note: This is a simpler example of what I really want. An enum won't work for me here.

public class SampleRequest
    {
        //Can only be "A" or "B"
        public string Property1 { get; set; }
    }

I am trying to create a schema filter that can output as the OpenAPI "OneOf" attribute.

https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#section-5.5.5

https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#oneof

https://github.com/domaindrivendev/Swashbuckle.AspNetCore#schema-filters

public class CustomSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {

            schema.OneOf = new List<OpenApiSchema>
            {

                new OpenApiSchema {Type = "string", Description = "A"},
                new OpenApiSchema {Type = "string", Description = "B"}
            };
            
        }
    }

When running the swagger, swagger-ui correctly renders the "oneOf" description:

oneOf: List [ OrderedMap { "type": "string", "description": "A" }, OrderedMap { "type": "string", "description": "B" } ]

However, I was expecting the value of it to look more like

oneOf: [ "A", "B" ]

Is this possible? The people reading my swagger documentation aren't going to know what a List of OrderedMap is.

like image 379
Dave Loukola Avatar asked Nov 07 '22 07:11

Dave Loukola


1 Answers

In C# .NET Core 5: In order to automatically resolve oneOf (polymorphism) at compile-time for your swagger.json, add the following line in your Startup.cs:

public void ConfigureServices(IServiceCollection services){
     services.AddSwaggerGen(c => {c.UseOneOfForPolymorphism();})
}

For everything else, you can follow the documentation of OpenAPI 3.0.

like image 152
Julien Green Avatar answered Nov 15 '22 16:11

Julien Green