Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum values in Swagger

I created a Swagger schema filter like this:

public class OpenApiIgnoreEnumSchemaFilter : ISchemaFilter
{
    private readonly bool _useNames;

    public OpenApiIgnoreEnumSchemaFilter(bool useNames = false)
    {
        _useNames = useNames;
    }

    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (!context.Type.IsEnum && !(Nullable.GetUnderlyingType(context.Type)?.IsEnum ?? false))
        {
            return;
        }

        Type type = (context.Type.IsEnum ? context.Type : Nullable.GetUnderlyingType(context.Type));
        List<IOpenApiAny> list = new List<IOpenApiAny>();
        string[] names = Enum.GetNames(type);
        int[] values = Enum.GetValues(type).Cast<int>().ToArray();
        foreach (var (text, value) in names.Select((string name, int index) => (name, values[index])).ToList())
        {
            if (!type.GetMember(text)[0].GetCustomAttributes<OpenApiIgnoreEnumAttribute>().Any())
            {
                IOpenApiAny item;
                if (!_useNames)
                {
                    IOpenApiAny openApiAny = new OpenApiInteger(value);
                    item = openApiAny;
                }
                else
                {
                    IOpenApiAny openApiAny = new OpenApiString(text);
                    item = openApiAny;
                }

                list.Add(item);
            }
        }

        schema.Enum = list;
    }
}

It works quite well to a point - if I pass it the true value in the constructor argument and try to pick a value from a dropdown in the SwaggerUI in the browser it tells me that only integer values are allowed:

enter image description here

Is there a way to have the functionality provided by the schema filter (stringified enum names + hiding of some members I'd like to hide) and at the same time to be able to use those stringified enums in the UI?

like image 431
Marek M. Avatar asked Jul 20 '26 23:07

Marek M.


1 Answers

Set the schema.Type = "string"; and schema.Format = null;

Swagger will show enum names, and will pass the string value into the API. The controller and serializer should be able to handle enum values as strings.

like image 100
Alberto Avatar answered Jul 23 '26 13:07

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!