# Module 1: Fundamentals and the Endpoint Pipeline

**9:20 – 10:30 AM** · Concepts 25 min · [Lab](lab.md) 45 min

[▶ **Present this module**](../slides/module-1.html)

## Learning objectives

By the end of this module you can explain what happens between `WebApplication.CreateBuilder` and `app.Run()`, organize endpoints with route groups, bind parameters from every source, return strongly typed results, and read your API's OpenAPI document.

## Anatomy of Program.cs

A Minimal API has four parts, and every line in `Program.cs` belongs to one of them.

```csharp
var builder = WebApplication.CreateBuilder(args);   // 1. the builder

builder.Services.AddOpenApi();                        // 2. services (DI)

var app = builder.Build();

app.UseHttpsRedirection();                            // 3. middleware pipeline

app.MapGet("/health", () => "Healthy");               // 4. endpoints
app.MapOpenApi();

app.Run();
```

"Minimal" describes the number of abstractions between you and HTTP, not the number of things the framework can do. Everything ASP.NET Core offers, from authentication to output caching, plugs into the same builder and pipeline.

## Coming from controllers

If you have written `[ApiController]` classes, the mapping is direct. What was implicit in a controller becomes an explicit choice in a Minimal API, which is the point.

| Controller world | Minimal API world |
|---|---|
| `[Route("api/[controller]")]` on a class | `app.MapGroup("/api/products")` |
| `[HttpGet("{id}")]` on a method | `group.MapGet("/{id}", handler)` |
| `[FromBody]`, `[FromQuery]` inferred by `[ApiController]` | Inferred the same way, with `[AsParameters]` for grouping |
| `ActionResult<T>` | `Results<Ok<T>, NotFound>` via `TypedResults` |
| Action filters | Endpoint filters (`AddEndpointFilter`) |
| `ModelState` automatic 400 | `AddValidation()` automatic 400 (Module 2) |
| `[Authorize]` | `.RequireAuthorization()` on an endpoint or group (Module 3) |

## Route groups and feature folders

A `Program.cs` with sixty `MapGet` calls is not minimal, it is a mess. Group endpoints by feature and give each feature an extension method:

```csharp
// Endpoints/ProductEndpoints.cs
public static class ProductEndpoints
{
    public static RouteGroupBuilder MapProductEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/products")
                       .WithTags("Products");

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

        return group;
    }

    // handlers below…
}
```

```csharp
// Program.cs
app.MapProductEndpoints();
```

Anything you apply to the group, such as a tag, a filter, an authorization policy, or a cache policy, applies to every endpoint inside it. That is how Module 3 locks down all staff endpoints in one line.

## Route constraints

`{id:int}` is a route constraint: the segment must parse as an integer or the route does not match. A non-matching request never reaches binding, so `/api/products/abc` gets a `404`, the same as any unknown URL. Drop the constraint and the route matches, binding to `int id` fails, and the client gets a `400`. Constraints compose (`{id:int:min(1)}`), and a literal segment such as `/featured` always takes precedence over a parameter segment, constrained or not.

## Services and lifetimes

Everything you register on `builder.Services` gets a lifetime. **Transient** creates a new instance every time one is requested, **scoped** creates one per HTTP request, and **singleton** creates one for the life of the app. Lab 1's in-memory catalog is a singleton because its list *is* the data store; any shorter lifetime would reseed it and lose what you `POST`. A singleton is shared by every concurrent request, so the catalog guards its list with a lock. In Module 2 the EF Core version becomes scoped, matching the `DbContext` it wraps.

## Parameter binding

Handlers are plain methods, and the framework binds each parameter from the most sensible source.

```csharp
static async Task<Ok<List<ProductDto>>> GetProducts(
    [AsParameters] ProductQuery query,      // ?roast=&inStock= bundled into a record
    IProductCatalog catalog,                // resolved from DI
    CancellationToken ct)                   // the request's cancellation token
```

```csharp
public record ProductQuery(string? Roast, bool? InStock);
```

| Source | How it binds |
|---|---|
| Route `/{id}` | Parameter with a matching name |
| Query string | Simple types not matched by a route value |
| Body | A complex type on `POST`, `PUT`, `PATCH` |
| Header | `[FromHeader(Name = "X-Request-Id")]` |
| Services | Any registered service, or `[FromServices]` to be explicit |
| Special | `HttpContext`, `HttpRequest`, `CancellationToken`, `ClaimsPrincipal` |

When binding fails, for example a `?inStock=maybe` that cannot become a `bool`, the client gets a `400` before your handler runs. (A route constraint failure is different: the route never matches, so it is a `404`.) You will make that response consistent with `ProblemDetails` in Module 2.

## DTOs, not domain models

`Product` is the domain model: it has a `Roast` enum and a `StockQuantity`. `ProductDto` is the contract: it exposes `Roast` as a string and collapses stock into `InStock`. Keeping them separate means you can rename a column, add an internal field, or change how stock is tracked without breaking a client. `Roast` is a string in the DTO so the JSON reads `"Dark"` rather than `2`, and so adding a roast later is not a breaking change to a numeric contract. The cost is a small mapping step (`ToDto()`), and the risk is that string input needs validating, which is Module 2's job.

## TypedResults, not Results

`Results.Ok(product)` compiles, but it tells neither the compiler nor OpenAPI what your endpoint returns. `TypedResults` does both:

```csharp
static async Task<Results<Ok<ProductDto>, NotFound>> GetProduct(
    int id, IProductCatalog catalog, CancellationToken ct)
{
    var product = await catalog.FindAsync(id, ct);
    return product is null
        ? TypedResults.NotFound()
        : TypedResults.Ok(product.ToDto());
}
```

The `Results<T1, T2, T3>` union in the return type is the contract. If you try to return something not in the union, it is a compile error, and the OpenAPI document lists both a `200` with a schema and a `404`.

## CreatedAtRoute and the Location header

A `POST` that creates something should return `201 Created` and a `Location` header telling the client where the new resource lives. `TypedResults.CreatedAtRoute(dto, "GetProduct", new { id = product.Id })` builds that URL from the named route and its values, so you never hand-assemble a path string. If you change the `GetProduct` route template later, the `Location` header follows. The response body is the created resource, which saves the client a round trip.

## Endpoint filters

A filter wraps a handler. It runs after routing and binding, so it sees the bound arguments, which is something middleware cannot do. (`WebApplication` adds routing at the very start of the pipeline, so your middleware already knows which endpoint matched; it just runs before binding.)

```csharp
group.AddEndpointFilter(async (context, next) =>
{
    var sw = Stopwatch.StartNew();
    var result = await next(context);
    context.HttpContext.Response.Headers["X-Elapsed-Ms"] =
        sw.ElapsedMilliseconds.ToString();
    return result;
});
```

Order matters: middleware runs outside filters, filters run outside the handler.

```mermaid
flowchart LR
    R[Request] --> Rt[Routing] --> M1[Middleware] --> B[Binding] --> F[Endpoint filters] --> H[Handler]
    H --> F --> M1 --> Rs[Response]
```

## OpenAPI in .NET 10

Document generation comes from a first-party package, `Microsoft.AspNetCore.OpenApi`; no Swashbuckle required.

```csharp
builder.Services.AddOpenApi();
// …
app.MapOpenApi();                      // serves /openapi/v1.json
```

For a browsable UI, add the Scalar package and one line:

```csharp
app.MapScalarApiReference();           // serves /scalar/v1
```

Metadata flows into the document from the code you already wrote: the return-type union, `.WithName`, `.WithSummary`, `.WithDescription`, and `.Produces<T>()` where the type cannot be inferred. The lab has you fix a deliberately wrong `Produces` so you can see how a mismatch looks.

### Keeping endpoints out of the document

Not every endpoint belongs in your public contract. Health probes, internal callbacks, and diagnostics still need to work, but clients should not see them. `.ExcludeFromDescription()` removes an endpoint from the OpenAPI document without changing its behavior: it still routes and responds, it just is not listed.

!!! tip
`.WithName("GetProduct")` is not decoration. `TypedResults.CreatedAtRoute("GetProduct", ...)` looks the name up at runtime and throws if it is missing. Name every endpoint you will ever link to.
!!!

## Head to the lab

You now have everything you need to build the public menu: [Lab 1: The Public Menu](lab.md).
