Updating with PUT
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 9 of 20.
A PUT request replaces the resource at an address with the body it sends. Its lambda takes a route parameter and a body together:
app.MapPut("/notes/{id:int}", (int id, NewNote input) =>
{
var index = notes.FindIndex(n => n.Id == id);
if (index == -1)
return Results.NotFound();
notes[index] = new Note(id, input.Text);
return Results.Ok(notes[index]);
});FindIndex returns the position of the first match, or -1. A record cannot be changed after it is made, so the endpoint builds a new one with the same id and puts it in that position. Sending the same PUT twice gives the same result; sending the same POST twice adds two resources.
Challenge
EasyClients can change a recipe.
- In
Program.cs, mapPUT /api/recipes/{id:int}. Its lambda takesint idandNewRecipe input. - Find the recipe's position with
recipes.FindIndex(r => r.Id == id). When it is-1, returnResults.NotFound(new { error = $"Recipe {id} not found" }). - Otherwise make
new Recipe(id, input.Name, input.Category, input.Minutes), put it in that position ofrecipes, and returnResults.Ok(recipe).
Try it: press Run, pick PUT, path /api/recipes/2, body {"name":"Banana Pancakes","category":"breakfast","minutes":20}, and Send: status 200 with {"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20}. Send GET /api/recipes: three recipes, Banana Pancakes in the middle. A PUT to /api/recipes/99 answers 404.
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) =>
{
if (string.IsNullOrWhiteSpace(input.Name))
return Results.BadRequest(new { error = "Name is required" });
if (input.Minutes <= 0)
return Results.BadRequest(new { error = "Minutes must be more than 0" });
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
2Results and JSON Bodies
Ok and Not Found