DEV Community

Cesar Aguirre
Cesar Aguirre

Posted on • Originally published at canro91.github.io

TIL: Always Wrap Collections in API Responses

I originally posted this post on my blog.


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("/movies", () =>
{
    return new[] { "Titanic", "Terminator" };
    //     πŸ‘†πŸ‘†
    // Please don't.
    // Otherwise a cute baby panda dies in the forest
});

app.Run();
Enter fullscreen mode Exit fullscreen mode

Instead, please do:

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

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

app.Run();
Enter fullscreen mode Exit fullscreen mode

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 just to return an extra field.

Make this an API commandment.


If you're on your journey from junior/mid-level to senior, I wrote Street-Smart Coding: 30 Ways to Get Better at Coding. It's not a textbook. It's the roadmap I wish I had on my journey to become a senior coder.

That's 30 lessons to level up your coding skills. From Googling to debugging to clear communication. Some lessons are conventional. Others not so much. But all battle-tested.

Get your copy of Street-Smart Coding here

Top comments (0)