Menu
CoddyTech

Route Groups

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

Endpoints of one resource share the start of their routes. app.MapGroup(prefix) makes a route group: every endpoint mapped on it gets the prefix in front of its own pattern.

var orders = app.MapGroup("/api/orders");
orders.MapGet("/", () => orderList);
orders.MapGet("/{id:int}", (int id) => orderList.FirstOrDefault(o => o.Id == id));
orders.MapDelete("/{id:int}", (int id) => orderList.RemoveAll(o => o.Id == id));

The routes are /api/orders/, /api/orders/{id:int} and the DELETE on the same pattern. GET /api/orders matches /api/orders/, since a trailing slash does not change which route matches. The prefix is written once, so renaming it changes one line, and a group can apply settings to all its endpoints, such as requiring a login. Writing the prefix again inside the group doubles it: /api/orders/api/orders/{id:int}.

challenge icon

Challenge

Easy

Learners can keep favorite recipes. The three favorites endpoints share one group.

  1. In Program.cs, below nextId, add var favoriteIds = new List<int>();.
  2. Above app.Run(), make the group: var favorites = app.MapGroup("/api/favorites");.
  3. On the group, map GET "/": it returns the recipes whose Id is in favoriteIds, in the order of recipes.
  4. Map POST "/{id:int}": when no recipe has that id, return Results.NotFound(new { error = $"Recipe {id} not found" }). Otherwise add the id unless favoriteIds already holds it, and return Results.NoContent().
  5. Map DELETE "/{id:int}": remove the id from favoriteIds and return Results.NoContent().

Try it: press Run: GET /api/favorites answers []. Send POST /api/favorites/2 with an empty body: status 204. Send GET /api/favorites: a list with the Pancakes recipe. POST /api/favorites/99 answers 404, and DELETE /api/favorites/2 empties the list again.

Try it yourself

using Microsoft.AspNetCore.Http.HttpResults;

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.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
    var index = recipes.FindIndex(r => r.Id == id);
    if (index == -1)
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
    recipes[index] = recipe;
    return Results.Ok(recipe);
});

app.MapDelete("/api/recipes/{id:int}", Results<NoContent, NotFound> (int id) =>
{
    var removed = recipes.RemoveAll(r => r.Id == id);
    return removed > 0 ? TypedResults.NoContent() : TypedResults.NotFound();
});

app.Run();
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Minimal APIs