How to add example responses in Swagger in a ASP .NET minimal API?
Asked Answered
W

1

4

I would like to add examples of answers for my endpoints in my minimal API in .NET 7.

I have already found several interesting resources but none of them work in the context of a minimal API:

These are the kind of renderings I expect, i.e. a status code, with its description and a specific endpoint (e.g. suppose I have several 400 responses for different cases, I want to be able to differentiate them with a different description and response example).

For example, let imagine that I have the following Startup :

public class Startup
    {
        public IConfiguration Configuration
        {
            get;
        }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            /* ... */
            // Swagger services
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(BuilderUtils.SwaggerOptions());             
            /* ... */
        }
        public void Configure(WebApplication app)
        {
            // Swagger activation
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

        /* ... */



            app.MapMyEndpoints();

            app.Run();
        }
    }
}

With the following method:

public static void MapMyEndpoints(this WebApplication app)
{
    app.MapGet("/api/foo", () => return await Foo())
        .WithOpenApi(op => new(op)
        {
            OperationId = "MyOperationId",
            Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
            Summary = "MySummary",
            Description = "MyDescription"
        });

    app.MapGet("/api/bar", () => return await Bar())
        .WithOpenApi(op => new(op)
        {
            OperationId = "MyOperationId",
            Tags = new List<OpenApiTag> { new() { Name = "MyTag" } },
            Summary = "MySummary",
            Description = "MyDescription"
        });
}

Both will respond using the MessageBody class :

public class MessageBody
{
    public string? Message { get; set; }
        public string? Error { get; set; }
}

For example, Foo will respond either a 200 with the MessageBody : Message = "Connected",

or 400 with the MessageBody : Error = "Wrong Password" or Error = "Account not found"

And it goes on for the other endpoints.

I want to report all of those cases in my Swagger.

Because I work using minimal API, I can't use Exemple Filters, or if I can, I don't know how.

If anyone have a hints on how I can do that I will be really gratefull !

Wanderlust answered 17/5, 2023 at 12:50 Comment(0)
R
8

Install the Swashbuckle.AspNetCore.Filters nuget and then you can mark handlers with corresponding attributes:

builder.Services.AddSwaggerGen(options => options.ExampleFilters());
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

// ...

app.MapGet("/api/bar",
        [SwaggerResponseExample((int)HttpStatusCode.OK, typeof(MessageBodyOkExample))]
        [SwaggerResponseExample((int)HttpStatusCode.BadRequest, typeof(MessageBody400Example))]
        () => new MessageBody
        {
            Message = "Connected"
        })
    .WithOpenApi(op => new(op)
    {
        // ...
    })
    .Produces<MessageBody>((int)HttpStatusCode.OK)
    .Produces<MessageBody>((int)HttpStatusCode.BadRequest);

And sample responses:

public class MessageBodyOkExample : IExamplesProvider<MessageBody>
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Message = "Connected"
        };
    }
}

public class MessageBody400Example : IExamplesProvider<MessageBody>
{
    public MessageBody GetExamples()
    {
        return new MessageBody()
        {
            Error = "testError"
        };
    }
}

And result:

enter image description here

Note that according to the Swashbuckle.AspNetCore.Filters' documentation, it's not recommended to use filters unless you need to generate examples at runtime. It is probably the case for OP, but in many cases it might not be.

Since May 2018, Swashbuckle.AspNetCore supports adding examples via XML comments:

public class Product
{
    /// <summary>
    /// The name of the product
    /// </summary>
    /// <example>Men's basketball shoes</example>
    public string Name { get; set; }
}

This works for request examples and response examples, and it even works for example querystring and route parameters, i.e. on GET requests!

Rammer answered 17/5, 2023 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.