Swagger and human readable enums. How to?

Swagger
is a very powerful tool and it eases the process of exchanging and discussing the documentation between developers, testers, devops and other teams. Sometimes even other companies. That’s why it is very important to keep it as much human readable as possible.
Sadly, with the default settings for Swagger
and enum types it returns its underlying values instead of something meaningful. Unless you consider „1
” to be more meaningful than „Day
” for instance. Then you are good to go and this post is definitely not for you.
I’ve added a class WeatherForecastResult
to the default implementation of example WeatherForecastController
available after creating the default API project in Visual Studio. Its definition is as follows:
public class WeatherForecastResult
{
public WeatherForecastType Type { get; set; }
public string Data { get; set; }
}
public enum WeatherForecastType
{
Day,
Week,
Month,
Year
}
Pretty dummy implementation, just for demonstration purposes. In Swagger
it presents this way:

However, there is a simple way to achieve the following result:

To do this, simply add a line cfg.SchemaFilter<EnumSchemaFilter>();
to ConfigureServices
method inside services.AddSwaggerGen
. The EnumSchemaFilter
is a custom filter defined as follows:
internal sealed class EnumSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();
Enum
.GetNames(context.Type)
.ToList()
.ForEach(name => model.Enum.Add(new OpenApiString($"{name}")));
model.Type = "string";
model.Format = string.Empty;
}
}
}
And that’s all folks 🙂 all is setup and should run like a charm. Happy coding 🙂