Ok and Not Found
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 6 of 20.
An endpoint that can answer in more than one way returns a result from Results, which sets the status code. Results.Ok(value) is 200 with the value as JSON, and Results.NotFound() is 404 Not Found, the code for something that does not exist.
app.MapGet("/books/{id:int}", (int id) =>
{
var book = books.FirstOrDefault(b => b.Id == id);
if (book is null)
return Results.NotFound(new { error = "No such book" });
return Results.Ok(book);
});Every return goes through Results, so they share one type, IResult, and the lambda compiles. new { error = "No such book" } is an anonymous object: ASP.NET Core writes it as {"error":"No such book"}, a body that tells the client what went wrong.
Challenge
EasyGET /api/recipes/99 answers 200 with null. A client cannot tell that from a recipe that exists, so it should answer 404.
- In
Program.cs, give theGET /api/recipes/{id:int}lambda a block body,{ ... }, that finds the recipe withFirstOrDefault. - When it is
null, returnResults.NotFound(new { error = $"Recipe {id} not found" }). For id 99 the body is{"error":"Recipe 99 not found"}. - Otherwise return
Results.Ok(recipe).
Try it: press Run. GET /api/recipes/99 answers status 404 with {"error":"Recipe 99 not found"}. Send GET /api/recipes/2: status 200 and the Pancakes recipe, as before.
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),
};
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) => recipes.FirstOrDefault(r => r.Id == id));
app.Run();
All lessons in Minimal APIs
2Results and JSON Bodies
Ok and Not Found