Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 182 ยท ASP.NET Core

Minimal APIs

Build HTTP APIs with ASP.NET Core minimal APIs - MapGet, MapPost, MapPut, MapDelete, parameter binding, TypedResults, JSON, status codes, route groups and clean project organization.

A minimal API is the shortest way to build an HTTP service in ASP.NET Core. Instead of controller classes and attributes, you map a URL and an HTTP method straight to a function:

C#
app.MapGet("/hello", () => "Hello!");

"Minimal" does not mean small or toy. Minimal APIs use the same routing, dependency injection, authentication, validation and JSON machinery as the other styles, are very fast, and are the recommended starting point for new HTTP APIs. They are called minimal because there is very little ceremony between you and your logic.

In this lesson you will map the four main HTTP verbs, see how parameters are filled in automatically, return proper status codes with TypedResults, group related endpoints, and organize a growing API. We run every server inside the example and call it with HttpClient, as in the ASP.NET Core Overview.

Several examples below use a small in-memory list as the "database" so that you can run everything without extra packages. Real apps would replace it with a database (Data Access in .NET). The list is shared by all requests, so a real implementation must be thread safe; ours is only used one request at a time.

The four verbs

REST-style APIs map the HTTP method to the intention:

Method Mapped with Typical meaning
GET MapGet Read something; must not change data.
POST MapPost Create something (or run an action).
PUT MapPut Replace an existing thing.
PATCH MapPatch Change part of a thing.
DELETE MapDelete Remove a thing.

MapMethods("/path", ["GET", "HEAD"], handler) handles any combination, and Map("/path", handler) handles all methods. The handler can be a lambda, a local function, or a method group (app.MapGet("/todos", TodoHandlers.GetAll)).

C# Mapping the verbs

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 record NewName is the request body. A parameter of a complex type on POST/PUT is read from the JSON body automatically; an int that matches a in the route comes from the URL. You never touched a JSON library: the framework deserialises the request and serialises the response (a List<string> became a JSON array).

Where do parameters come from?

For each parameter of your handler, the framework decides the source by a short list of rules, checked in this order:

  1. An attribute you wrote says where: [FromRoute], [FromQuery], [FromHeader], [FromBody], [FromForm], [FromServices].
  2. If the name matches a route template placeholder, it comes from the route.
  3. Special types are provided: HttpContext, HttpRequest, HttpResponse, CancellationToken, ClaimsPrincipal.
  4. Registered service types come from the DI container.
  5. Simple types (int, string, Guid, DateOnly, enums, ...) come from the query string.
  6. Any other complex type is read from the JSON body.

That is enough for most endpoints. The next lesson, Routing and Model Binding, goes through the rules, constraints and customizations in depth.

C# Route, query, header and service parameters

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.

Look at the last two requests. A missing required parameter (quantity) is a client error, 400 Bad Request. A route that fails the :int constraint (abc) does not match the endpoint at all, so the result is 404 Not Found. Nullable parameters (int? discount) and parameters with default values are optional.

In Development, the framework logs a clear message for a failed binding (for example Required parameter "int quantity" was not provided from query string). Keep logging on while you develop; it saves a lot of guessing.

Returning results

What your handler returns decides the response:

  • string becomes text/plain.
  • A record, class, array or list becomes JSON with status 200.
  • void or Task gives 200 with an empty body.
  • An IResult lets you choose the status code, headers and body.

You create IResult values with the static class Results or its sibling TypedResults. They offer the same helpers (Ok, Created, NoContent, BadRequest, NotFound, Conflict, Problem, File, Redirect, ...). Prefer TypedResults: it returns a concrete type such as Ok<Todo> or NotFound, which the compiler and the OpenAPI generator can see.

C# Status codes with TypedResults

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.

Each outcome has the status code you would expect from a well-behaved API: 201 Created includes a Location header pointing at the new resource, 204 No Content says "done, nothing to return", and 404 and 400 explain what went wrong.

The Results<Ok<Todo>, NotFound> return type is a union: the handler may return exactly those types and nothing else. The compiler checks every return statement, and the generated OpenAPI document lists both responses without extra attributes. Notice that the lambda has an explicit return type before the parameter list. That is a C# lambda feature (C# 10) which minimal APIs rely on here.

Results versus TypedResults

Results.Ok(x) returns the general IResult interface, which hides the details. TypedResults.Ok(x) returns Ok<T>, which tests can inspect directly:

C#
// A unit test can call the handler as an ordinary method:
var result = TodoHandlers.Get(1, todos);                // Results<Ok<Todo>, NotFound>
var ok = Assert.IsType<Ok<Todo>>(result.Result);        // read-only: xUnit is not available here
Assert.Equal("Learn C#", ok.Value!.Title);

That testability is one of the main reasons to prefer TypedResults.

Returning JSON and controlling serialization

The framework uses System.Text.Json with web defaults: camelCase property names, case-insensitive reading, numbers in quotes not accepted. If you want different behavior globally, configure it once:

C#
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

For one response, TypedResults.Json(value, options) overrides it. See JSON with System.Text.Json for naming policies, converters and attributes such as [JsonPropertyName].

Route groups: share a prefix and settings

APIs repeat themselves: /todos, /todos/{id}, /todos again. MapGroup removes the repetition. A group has a common prefix, and you can attach metadata, filters, authorization, or tags once to the whole group.

C# MapGroup 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.

Groups nest, so /api/v1 plus /books plus /{id:int} becomes /api/v1/books/{id:int}. The filter added to the outer group ran for the inner endpoints too. Typical group-level settings: .RequireAuthorization(), .WithTags("...") (organizes the OpenAPI document), .AddEndpointFilter(...), .WithOpenApi(), .RequireRateLimiting("api").

.WithName("GetTodo") gives an endpoint a stable name. Together with TypedResults.CreatedAtRoute or LinkGenerator, you can build URLs from names instead of repeating strings, so renaming a route does not break the links.

C#
app.MapGet("/todos/{id:int}", (int id) => ...).WithName("GetTodo");

app.MapPost("/todos", (NewTodo input) =>
{
    var todo = Save(input);
    return TypedResults.CreatedAtRoute(todo, "GetTodo", new { id = todo.Id });
});

Handlers as methods and files

Lambdas are great for the first ten endpoints. After that, Program.cs becomes a long list. Experienced teams organise a minimal API in one of these ways:

  • Static handler classes: each feature gets a class with static methods, and a mapping extension method registers them. Program.cs stays small.
  • One file per feature ("vertical slice"): request type, validation, handler and mapping together.
C# An extension method per feature

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 handlers are ordinary static methods, so they are readable, testable without HTTP and independent of the lambda syntax. Program.cs now only says what features exist. In a real project each feature would live in its own file, and the in-memory store would be replaced by a repository on top of a database.

Asynchronous handlers and cancellation

Handlers that call databases or other services should be async. Ask for a CancellationToken parameter: the framework supplies the request's token, which is cancelled when the client disconnects, so you stop work nobody is waiting for.

C#
app.MapGet("/report", async (ReportService reports, CancellationToken cancellationToken) =>
{
    Report report = await reports.BuildAsync(cancellationToken);
    return TypedResults.Ok(report);
});

Common mistakes

  • Using GET to change data. GET must be safe: browsers, crawlers and caches may repeat it.
  • Returning entities straight from the database. Return DTOs (small records for the API), so you control exactly what leaves the server and can change the database without breaking clients.
  • Forgetting that the in-memory list is shared. Any collection in a singleton is touched by many requests at once. Use a database or concurrent collections (Concurrent Collections).
  • async void or blocking calls in handlers. Return Task and await.
  • Everything in Program.cs. Fine for a demo, painful at scale. Group endpoints and move handlers out.
  • Trusting input. Binding only checks types. Validate values (see Validation and Problem Details) and secure sensitive endpoints (Authentication and Authorization).
  • Mixing a body with [FromForm] or reading the body twice. The request body is a stream that can be read once. Bind it to one parameter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In app.MapPost("/todos", (NewTodo input) => ...), where does input come from?

    A complex type that is not a registered service and not a simple type is bound from the JSON request body.
  2. 2. Which return value produces a 201 Created response with a Location header?

    Created sets status 201, writes the Location header from the URI you pass and serialises the value as the body.
  3. 3. Why prefer TypedResults over Results?

    TypedResults.Ok(x) returns Ok<T> rather than the general IResult, so the framework and your tests can see the exact response type.
  4. 4. What does app.MapGroup("/api/v1") give you?

    Route groups reduce repetition: the prefix and any metadata or filters applied to the group apply to every endpoint inside, and groups can be nested.
  5. 5. A request to /products/abc hits an endpoint mapped as /products/{id:int}. What is the result?

    Route constraints take part in matching. When abc fails :int, the route does not match and the framework answers with 404. A query-string value that cannot be converted gives 400 instead.

Summary

  • Minimal APIs map HTTP verbs and URLs straight to functions with MapGet, MapPost, MapPut, MapPatch and MapDelete.
  • Parameters are bound automatically: route values, query string, headers, JSON body, services and special types like HttpContext and CancellationToken.
  • Return plain values for 200 or TypedResults (Ok, Created, NoContent, BadRequest, NotFound) for exact status codes; Results<A, B> documents all outcomes.
  • MapGroup shares a prefix, tags, filters and authorization across endpoints and can be nested.
  • Keep Program.cs small: put handlers in static methods or classes and register each feature with an extension method.
  • Return DTOs, validate input, make handlers async, and never let shared in-memory state go unprotected.

Next: Routing and Model Binding