Search code examples
c#asp.net-coreswaggerswagger-uiminimal-apis

Swagger for Minimal API


I'm trying to use minimal API in my project. the problem I'm facing is that the traditional Controllers are in a way that swagger generates a seperate section for each and every Controller. but I can't see an option to add this kind of seperation in Minimal API. is it possible to add different sections in Swagger using minimal API?


Solution

  • You can use WithTags extension method:

    OpenAPI supports using tag objects to categorize operations. These tags are typically used to group operations in the Swagger UI. These tags can be added to an operation by invoking the WithTags extension method on the endpoint with the desired tags.

    app.MapGet("/one", () => "Hello World!").WithTags("xyz");
    app.MapGet("/two", () => "Hello World!").WithTags("xyz");
    

    enter image description here

    It pairs very nicely with MapGroup:

    The MapGroup extension method helps organize groups of endpoints with a common prefix. It reduces repetitive code and allows for customizing entire groups of endpoints with a single call to methods like RequireAuthorization and WithMetadata which add endpoint metadata.

    var adminGroup = app.MapGroup("/admin")
        .WithTags("admin");
    adminGroup.MapGet("/adminThing", () => "some");
    adminGroup.MapPost("/doAdminThing", () => "some1");
    
    var userGroup = app.MapGroup("/user")
        .WithTags("user");
    userGroup.MapGet("/userThing", () => "some");
    userGroup.MapPost("/doUserThing", () => "some1");
    

    enter image description here