Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 52 ยท Routing and Minimal APIs

Minimal API Endpoints

Write minimal API endpoints with MapGet, MapPost, MapPut and MapDelete, choose return types, and use Results and TypedResults to send correct status codes.

A minimal API is a set of HTTP endpoints declared directly in code, without controllers or base classes. Each endpoint says three things: which HTTP method, which URL pattern and which handler runs. That is all you need to build a real JSON API, and the style scales surprisingly far.

In this lesson you will build a small in-memory "notes" API with all four classic verbs, learn what each handler may return, and see why status codes matter. You will use Results and TypedResults to say "created", "not found" or "no content" precisely instead of always answering 200.

One method per verb

Each HTTP verb has a Map method on the app. They follow the REST convention you will see everywhere.

Method Verb Typical meaning Typical success status
MapGet GET Read a resource or a list 200 OK
MapPost POST Create a resource 201 Created
MapPut PUT Replace a resource 200 OK or 204 No Content
MapPatch PATCH Change part of a resource 200 OK or 204 No Content
MapDelete DELETE Remove a resource 204 No Content

GET must never change data on the server, so clients and caches can repeat it safely. PUT and DELETE are idempotent: doing them twice leaves the same final state. POST is not, because posting twice usually creates two things.

All the Map methods take a route pattern and a handler. The handler is any delegate: a lambda, a local function or a method group. For other verbs, use MapMethods("/path", new[] { "HEAD" }, handler).

A first CRUD API

The following program keeps notes in a dictionary and exposes the four verbs. Do not worry about the parameter details yet; route templates and parameter binding have their own lessons. For now, in the pattern becomes the id parameter, and a parameter of a custom type is read from the JSON body.

C# Four verbs, one resource

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.

Read the output as a conversation. The POST returned 201 Created with a Location header pointing at the new resource, so a client knows where to find it. PUT and DELETE returned 204 No Content (success, nothing to say). Once deleted, a GET for the same id returned 404. This is how a well-behaved HTTP API talks.

The dictionary in this example is shared by all requests. With real concurrent traffic you would need a thread-safe collection or a database. We keep it simple to focus on endpoints; Data Access without an ORM shows safer storage.

What a handler can return

ASP.NET Core inspects the handler's return value and writes the response accordingly:

Return type What the framework does
string 200, text/plain
T (object, record, collection, number) 200, serialized as JSON
IResult (from Results) Executes the result: any status code, body or headers
Task<...> / ValueTask<...> Awaits, then treats the value as above
void / Task 200 with an empty body

An IResult gives you control. The Results class has factory methods for the common cases:

Method Status Notes
Results.Ok(value) 200 JSON body
Results.Created(uri, value) 201 adds the Location header
Results.Accepted() 202 work queued, not yet done
Results.NoContent() 204 no body
Results.BadRequest(error) 400 the request is malformed
Results.NotFound() 404 no such resource
Results.Conflict() 409 state conflict, such as a duplicate
Results.StatusCode(418) any any code you like
Results.Problem(...) any RFC 9457 problem details body

Pick the status code that tells the client the truth. A "not found" answered with 200 and the text "not found" forces every client to parse your message. A proper 404 is understood by browsers, proxies, caches and every HTTP library.

Results or TypedResults?

Results.Ok(...) returns the general type IResult. TypedResults.Ok(...) returns a concrete type such as Ok<Note>. The behavior at runtime is the same; the difference is what the compiler and tools can see:

  • With TypedResults you can declare the possible outcomes in the return type: Results<Ok<Note>, NotFound>. The compiler checks that you return only those, and the OpenAPI generator can list the responses automatically.
  • Tests can assert on the concrete type (Assert.IsType<Ok<Note>>(...)) without running a server.

Here is the same lookup written both ways, and a look at the types you get back:

C# Results versus 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.

The two endpoints behave the same on the wire. The strict one documents its possible results in its signature, and you could unit-test it as a plain method, as the "direct call" lines show. Prefer TypedResults in new code, and read more in Responses, Results and Content Negotiation.

Lambdas, local functions and method groups

A handler is just a delegate, so you can organize it in whichever way keeps Program.cs readable. Short handlers stay inline; longer ones move to static methods:

C#
app.MapGet("/health", () => "ok");                 // inline lambda
app.MapGet("/notes/{id}", NoteHandlers.GetById);   // method group

Handlers that need data from the request or services from the container just declare parameters. The framework fills them in, which is the subject of Parameter Binding in Minimal APIs. When the file gets long, move groups of endpoints into extension methods, as shown in Route Groups and Organizing Endpoints.

Common mistakes

  • Returning 200 for failures. Use NotFound, BadRequest and friends so clients can react.
  • Doing work in MapGet. A GET that changes data breaks caching, prefetching and crawlers. Use POST, PUT or DELETE for changes.
  • Forgetting Created's URL. Results.Created(uri, value) needs the address of the new resource, not the address you were called at.
  • Mixing Results and a plain object in one handler. If one branch returns Results.NotFound() and another returns a Note, the lambda has no single return type, so the compiler complains. Wrap the success case in Results.Ok(...), as in the first example.
  • Blocking calls. Use async handlers and await I/O; see Your First Web App.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status code is the best answer to a successful POST that created a new resource?

    201 Created tells the client a resource was made, and the Location header says where it lives. Results.Created(uri, value) sets both.
  2. 2. A handler returns Results.NoContent(). What does the client receive?

    204 means success with nothing to return, the usual answer for PUT and DELETE.
  3. 3. What is the main benefit of TypedResults over Results?

    Behavior on the wire is the same. TypedResults gives the compiler and OpenAPI tooling exact type information.
  4. 4. Which verb should NOT change server state?

    GET is safe: clients, caches and crawlers may repeat it freely, so it must not have side effects.
  5. 5. A handler returns a record Note. What does the framework produce?

    Any non-IResult object is serialized to JSON with status 200.

Summary

  • Minimal API endpoints map a verb and a URL pattern to a handler: MapGet, MapPost, MapPut, MapPatch, MapDelete.
  • Handlers can return text, objects (JSON), IResult values or tasks of those.
  • Use Results or TypedResults to send precise status codes: 201 with Location, 204, 400, 404, 409.
  • TypedResults and Results<T1, T2> make the possible outcomes visible to the compiler, tests and OpenAPI.
  • GET never changes state; PUT and DELETE are idempotent.
  • Keep Program.cs short by moving handlers into methods and extension methods as the API grows.

Next: Route Templates and Constraints