← All posts
~/blog/designing-a-small-api-in-dotnet.md#dotnet #architecture

Designing a small API in .NET, the boring way

Most API problems are born before anyone opens an editor. Someone starts typing app.MapPost, and three weeks later the endpoints have names like /doThing2 and nobody remembers why.

The fix isn’t clever. It’s a few boring steps, done in order. I’ll walk through them with a deliberately silly example: an API that tells me which of my houseplants need water.

Step 1: say what it does in plain sentences

Before any URL or table, write what the thing does, like you’re explaining it to a friend.

  • I can add a plant, with a name and how often it needs water.
  • I can see my plants.
  • I can say “I watered this one”.
  • I can see which plants are thirsty.

That’s the whole app. If one sentence needs three “and”s, it’s really two sentences. Split it now, while splitting is free.

Step 2: nouns become resources, verbs become HTTP

Plants are a noun, so they get a URL. Watering a plant is something that happens, and I want to remember it happened, so I make it its own thing instead of a field on the plant:

text
GET   /plants
POST  /plants
GET   /plants/{id}
POST  /plants/{id}/waterings
GET   /plants?thirsty=true

I could have used PATCH /plants/{id} with a lastWatered field. It works, until I want to know how often I actually water things, or two requests arrive at once and one overwrites the other. A list of watering events gives me history for free and removes that race. That’s the kind of decision that’s cheap on day one and annoying on day ninety.

Step 3: check input at the door

Here’s the create endpoint as a minimal API:

csharp
public record CreatePlant(string Name, int WaterEveryDays);

app.MapPost("/plants", async (CreatePlant body, IPlantStore store, CancellationToken ct) =>
{
    var errors = new Dictionary<string, string[]>();

    if (string.IsNullOrWhiteSpace(body.Name))
    {
        errors["name"] = ["Name is required."];
    }

    if (body.WaterEveryDays is < 1 or > 365)
    {
        errors["waterEveryDays"] = ["Use a number between 1 and 365."];
    }

    if (errors.Count > 0)
    {
        return Results.ValidationProblem(errors);
    }

    var plant = await store.Add(body.Name.Trim(), body.WaterEveryDays, ct);
    return Results.Created($"/plants/{plant.Id}", plant);
});

A few small choices in there matter more than they look:

  • Bad input gets a 400 with a body that says what was wrong, per field. Whoever calls this API shouldn’t have to read your source code to learn what “invalid” means.
  • Success is a 201 Created with a Location header pointing at the new plant, not a bare 200.
  • The CancellationToken is passed all the way down. If the caller gives up, the database work can stop too.

Step 4: decide the boring things before they decide you

Three things are painful to add later and trivial to add now.

One error shape. Call builder.Services.AddProblemDetails() and every error comes back in the same format. Clients write one error handler instead of five.

Paging from the first list endpoint. A list that returns everything works fine with twelve plants and falls over with twelve thousand rows. Cap the page size so nobody can ask for the moon:

csharp
var size = Math.Clamp(pageSize, 1, 100);
var offset = (Math.Max(page, 1) - 1) * size;

Ids that aren’t a counter. If /plants/7 works, people will try /plants/8. Use GUIDs unless you have a reason not to.

Step 5: write down what you left out

My plant app has no login, no caching, no versioning and no webhooks. That’s fine for a plant app. What I’d do is put those in a short “not now” list in the README. Left out on purpose is a decision. Left out because nobody thought of it is a surprise waiting for a Friday afternoon.

The whole method, short

Write the sentences. Turn nouns into URLs. Validate at the door. Pick your boring defaults early. List what you skipped.

None of it is exciting, and that’s why it works. The exciting part of an API is whatever it does for the people using it.