TIL: Always Wrap Collections in API Responses

Note to future me:

You’ve learned this before. But it’s easy to forget or let teammates (or clients) make the same mistake.

Always return collections wrapped inside a response object from your APIs.

Adding fields, like pageNumber and itemCount, won’t break the UI or other clients. This is one of the few places where you should forget about YAGNI. Remember You Aren’t Gonna Need It? Is that still a guideline in the future with AI? Anyway…

Please, don’t do:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () =>
{
    return new[] { "Titanic", "Terminator" };
	//     ^^^^^
	// Please don't.
	// Otherwise a cute baby panda dies in the forest
});

app.Run();

Instead, please do:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () =>
{
    return new
    {
        Items = new[] { "Titanic", "Terminator" }
        // ^^^^
        // OK, with a proper object.
        // You know we're lazy with the examples
    };
});

app.Run();

Just today, in a client project, I realized we let this mistake happen and we had to update almost a dozens pages in a Blazor app.

Make this an API commandment.