I am trying to get the hang of swagger in minimal API. I have the following code:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(setup => setup.SwaggerDoc("v1", new OpenApiInfo()
{
Description = "An api that will change your life for ever",
Title = "Alert Api",
Version = "v1",
Contact = new OpenApiContact()
{
Name = "Grundfos",
Url = new Uri("https://grundfos.com")
}
}));
WebApplication app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//Map endpoints
app.MapGet("/alerts", async () => Results.Ok());
app.MapGet("/profiles", async () => Results.Ok());
this gives a swagger UI looking like this:
My question is: How do you sort the endpoints to be under a headline called "alerts" and "profiles"?
>Solution :
I think what you are after is something called Tags in swagger.
You can add WithTags at the end of your mapping, like so:
//Map endpoints
app.MapGet("/alerts", async () => Results.Ok()).WithTags("Alerts");
app.MapGet("/profiles", async () => Results.Ok()).WithTags("Profiles");
The result looks like this:
Alternatively you can also take another approach by configuring the AddSwaggerGen method.
In there you can take the first segment of the URL endpoint and use that as the tag name.
For example, the endpoints alerts and alerts/delete will both be placed in a section called alerts.
builder.Services.AddSwaggerGen(c =>
{
c.TagActionsBy(d =>
{
var rootSegment = d.RelativePath?
.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault() ?? "Home";
return new List<string> { rootSegment! };
});
})
//Map endpoints without 'WithTags`
app.MapGet("/alerts", async () => Results.Ok());
app.MapGet("/alerts/delete", async () => Results.Ok());
app.MapGet("/profiles", async () => Results.Ok());


