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:
- https://www.dotnetnakama.com/blog/enriched-web-api-documentation-using-swagger-openapi-in-asp-dotnet-core/#api-examples-request-and-response
- https://medium.com/@niteshsinghal85/multiple-request-response-examples-for-swagger-ui-in-asp-net-core-864c0bdc6619
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 !