Menu
CoddyTech

Bad Requests

Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 8 of 20.

A body can leave a property out: {} binds, and input.Email is null even though the record says string. Nullable reference types only warn when the code compiles; they never check JSON. So the endpoint checks the values itself and answers 400 Bad Request with Results.BadRequest before it changes anything.

app.MapPost("/signups", (Signup input) =>
{
    if (string.IsNullOrWhiteSpace(input.Email))
        return Results.BadRequest(new { error = "Email is required" });
    signups.Add(input);
    return Results.Created($"/signups/{signups.Count}", input);
});

string.IsNullOrWhiteSpace is true for null, for "" and for text of spaces only. The error body tells the client what to fix.

challenge icon

Challenge

Easy

POST /api/recipes refuses a recipe without a name or with no cooking time.

  1. In Program.cs, at the top of the POST lambda, when string.IsNullOrWhiteSpace(input.Name), return Results.BadRequest(new { error = "Name is required" }).
  2. Next, when input.Minutes <= 0, return Results.BadRequest(new { error = "Minutes must be more than 0" }).
  3. Both checks come before the recipe is made and added, so a refused recipe is never saved and does not use an id.

Try it: press Run and POST {"category":"soup","minutes":30} to /api/recipes: status 400 and {"error":"Name is required"}. POST {"name":"Toast","category":"breakfast","minutes":0}: {"error":"Minutes must be more than 0"}. Then POST {"name":"Waffles","category":"breakfast","minutes":20}: 201 with id 4.

Try it yourself

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

var recipes = new List<Recipe>
{
    new(1, "Tomato Soup", "soup", 25),
    new(2, "Pancakes", "breakfast", 15),
    new(3, "Lentil Soup", "soup", 40),
};
var nextId = 4;

app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
    recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id) =>
{
    var recipe = recipes.FirstOrDefault(r => r.Id == id);
    if (recipe is null)
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    return Results.Ok(recipe);
});

app.MapPost("/api/recipes", (NewRecipe input) =>
{
    var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
    recipes.Add(recipe);
    return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});

app.Run();

All lessons in Minimal APIs