bark.api/Program.cs
Tony Bark dc4af28f97 Add Swagger/OpenAPI support for BarkAPI
Integrated OpenAPI and Swagger UI for BarkAPI, including endpoint documentation and UI configuration for development environment. This will enhance API discoverability and testing during development.
2025-11-27 12:22:42 -05:00

71 lines
1.8 KiB
C#

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("TodoDb"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApiDocument(cfg =>
{
cfg.DocumentName = "BarkAPI";
cfg.Title = "BarkAPI v1";
cfg.Version = "v1";
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseOpenApi();
app.UseSwaggerUi(cfg =>
{
cfg.DocumentTitle = "BarkAPI";
cfg.Path = "/api";
cfg.DocumentPath = "/api/{documentName}/swagger.json}";
cfg.DocExpansion = "list";
});
}
app.MapGet("/", () => "Bark API");
app.MapGet("/todo", async (TodoDb db)
=> await db.Todos.ToListAsync());
app.MapGet("/todo", async (TodoDb db)
=> await db.Todos.Where(t => t.IsCompleted).ToListAsync());
app.MapGet("/todo/{id}", async (int id, TodoDb db) =>
await db.Todos.FindAsync(id) is Todo todo ? Results.Ok() : Results.NotFound());
app.MapGet("/todo", async (Todo todo, TodoDb db)
=>
{
db.Todos.Add(todo);
await db.SaveChangesAsync();
return Results.Created($"/todo/{todo.Id}", todo);
});
app.MapGet("/todo/{id}", async (int id, Todo input, TodoDb db) =>
{
var todo = await db.Todos.FindAsync(id);
if (todo is null) return Results.NotFound();
todo.Name = input.Name;
todo.IsCompleted = input.IsCompleted;
await db.SaveChangesAsync();
return Results.NoContent();
});
app.MapGet("/todo/{id}", async (int id, TodoDb db) =>
{
if (await db.Todos.FindAsync(id) is Todo todo)
{
db.Todos.Remove(todo);
await db.SaveChangesAsync();
return Results.NoContent();
}
return Results.NotFound();
});
app.Run();