Menu
CoddyTech

Route Parameters

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

One route per recipe would never end. A route parameter is a part of the path in braces: it matches any value in that place.

app.MapGet("/orders/{number}", (int number) => $"Order {number}");

GET /orders/42 answers Order 42. ASP.NET Core passes the value to the lambda parameter with the same name, and converts the text 42 to the parameter's type, here int. A parameter whose name is not in the route is looked for in the query string instead, and when it is not there either, the answer is 400 Bad Request. A status code is the number at the start of every response: 200 means OK, and codes from 400 to 499 mean the request was wrong.

challenge icon

Challenge

Easy

Each recipe gets its own address: /api/recipes/1, /api/recipes/2 and so on.

  1. In Program.cs, below GET /api/recipes, map GET /api/recipes/{id}.
  2. Its lambda takes int id and returns the recipe whose Id equals id. recipes.FirstOrDefault(r => r.Id == id) finds it.

Try it: press Run. GET /api/recipes/2 answers {"id":2,"name":"Pancakes","category":"breakfast","minutes":15}. Send GET /api/recipes/99: no recipe has that id, so FirstOrDefault returns null and the answer is status 200 with the body null. The next chapter answers 404 for it.

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", () => recipes);

app.Run();

All lessons in Minimal APIs