Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 52 ยท Routing and Minimal APIs

Route Groups and Organizing Endpoints

Organize minimal API endpoints with MapGroup: shared prefixes, nested groups, group-wide filters and metadata, and one extension method per feature.

A minimal API starts as a handful of app.MapGet calls in Program.cs. That is lovely for ten endpoints and miserable for a hundred. Soon every route repeats the same /api/v1/products prefix, half of them need the same authorization rule, and the file scrolls forever. Route groups solve the first two problems, and a small naming convention (one extension method per feature) solves the third.

In this lesson you will use MapGroup to share a prefix, nest groups, attach filters and metadata to a whole group at once, and split a growing application into feature files. If you have not seen plain endpoints yet, start with Minimal API Endpoints and Route Templates and Constraints.

MapGroup: one prefix for many endpoints

app.MapGroup("/api/products") returns a RouteGroupBuilder. You call the usual MapGet, MapPost and friends on it, and the prefix is put in front of every route template for you.

C# A group with a shared prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The three endpoints are registered as /api/products, /api/products/{id:int} and again /api/products for POST. Notice that the route "/" inside the group becomes the group's own address: GET /api/products reaches it (internally the pattern keeps a trailing slash, as the next example shows, and matching ignores it). A request without the prefix finds nothing and returns 404.

The group is not a separate application. It is only a convenient way to build endpoints, and when the app starts, each endpoint is an ordinary route with the full pattern. That is why a group costs nothing at request time.

Nested groups

Groups can contain groups. Each level adds its own prefix, so the inner endpoint gets the concatenation of all of them.

flowchart TD
    A["app"] --> B["MapGroup /api"]
    B --> C["MapGroup /v1"]
    C --> D["MapGroup /orders"]
    D --> E["GET /api/v1/orders"]
    D --> F["GET /api/v1/orders/{id}"]
    C --> G["MapGet /ping<br/>GET /api/v1/ping"]

Every nested group prepends its prefix, so a deeply nested endpoint gets the full path.

C# Nesting groups to build a versioned API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first loop proves the point from the previous section: after the app starts, groups are gone and only fully expanded route patterns remain. A group prefix may itself contain route parameters, for example app.MapGroup("/tenants/{tenant}"), in which case every endpoint inside can declare a tenant parameter.

An empty prefix is allowed: app.MapGroup("") has no path of its own. It is useful when you only want to attach filters or metadata to a set of endpoints, which is what the next section is about.

Conventions apply to the whole group

The real value of a group is that everything you call on the group builder applies to every endpoint inside it, including endpoints added later. These calls return the builder, so they chain:

  • RequireAuthorization() demands a signed-in user (Authorization covers the details)
  • AddEndpointFilter(...) runs a filter around each endpoint (Endpoint Filters)
  • WithTags, WithName, WithDescription, Produces<T> and WithMetadata attach metadata
  • RequireCors, RequireRateLimiting and CacheOutput pick policies by name

Metadata is plain objects stored on the endpoint. Middleware that runs after routing can read it through context.GetEndpoint(); that is how authorization, CORS and OpenAPI know what each endpoint wants. You can attach your own markers, too.

C# A group filter and group metadata

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two things are worth noticing. The filter protects both admin endpoints without being mentioned on either of them, and /public is untouched because it was not mapped through the group. And the group's tag and marker really did land on each endpoint's metadata list, next to the per-endpoint name.

Order matters a little: conventions added to the group before you map endpoints and after both apply. Filters you add to the group run outside filters you add to single endpoints, so group-level rules always see the request first.

One extension method per feature

Groups pair beautifully with extension methods. Give each feature its own file with a method that takes an IEndpointRouteBuilder and maps everything for that feature. Program.cs then reads like a table of contents.

C#
// Features/Products/ProductEndpoints.cs
public static class ProductEndpoints
{
    public static IEndpointRouteBuilder MapProductEndpoints(this IEndpointRouteBuilder routes)
    {
        RouteGroupBuilder group = routes.MapGroup("/api/products").WithTags("products");

        group.MapGet("/", ListProducts);
        group.MapGet("/{id:int}", GetProduct);
        group.MapPost("/", CreateProduct);

        return routes;
    }

    private static IResult GetProduct(int id) => Results.Ok(new { id });
    // ...
}

// Program.cs
app.MapProductEndpoints();
app.MapOrderEndpoints();

Passing the method name (a method group) as the handler, instead of a lambda, keeps the mapping code short and makes each handler a normal, testable method. The extension takes IEndpointRouteBuilder, not WebApplication, so it also works on a group: you could map the product endpoints inside a /v1 group in one line.

Here is that structure running end to end. Both features are separate static classes, and each can be moved to its own file without changing a character.

C# Features as extension methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Practical advice for larger apps

  • Group by feature, not by HTTP verb. Products, orders and users each get a file; do not make a "GETs" file.
  • Put cross-cutting rules on the group. Authorization, rate limiting and a shared validation filter belong on the group so nobody forgets them on a new endpoint.
  • Use WithName on endpoints you link to. Names must be unique across the whole app, so prefix them by feature (Products.Get).
  • Keep handlers small. An endpoint method should translate HTTP to a call into a service (Dependency Injection in ASP.NET Core) and back. Business rules do not belong in the mapping file.
  • Do not nest too deep. Three levels (/api, /v1, a feature) are usually enough to stay readable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does app.MapGroup("/api/products") return and what does it do to endpoints mapped on it?

    MapGroup returns a RouteGroupBuilder. Endpoints mapped on it get the group prefix in front of their route template, and conventions called on the group apply to all of them.
  2. 2. A filter is added with AddEndpointFilter on a group. Which endpoints does it run for?

    Conventions on a group apply to all endpoints mapped through it, including ones added later, but they do not affect endpoints mapped elsewhere.
  3. 3. Why are feature mapping methods usually written as extension methods on IEndpointRouteBuilder rather than on WebApplication?

    Both WebApplication and RouteGroupBuilder implement IEndpointRouteBuilder, so one extension method can map a feature at the root or inside any group.
  4. 4. What exists at request time after the app has started?

    Groups are resolved when endpoints are built. The endpoint data source holds normal route endpoints with their full patterns, so groups add no per-request cost.

Summary

  • MapGroup(prefix) returns a RouteGroupBuilder that prepends a shared prefix to every endpoint mapped on it.
  • Groups nest; each level adds its own prefix, and a prefix may contain route parameters.
  • Filters, authorization, tags, names and other metadata called on a group apply to all its endpoints.
  • Metadata is a list of plain objects on each endpoint that later middleware can read.
  • Write one Map<Feature>Endpoints(this IEndpointRouteBuilder) extension per feature so Program.cs stays short.
  • Group by feature, keep handlers thin and put shared rules on the group.

Next: Parameter Binding in Minimal APIs