Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you sort endpoints in swagger with the minimal api .net 6

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:

Swagger interface

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here


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());

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading