Skip to content
Tutorials Center
My learning

Topics

Lesson 140 of 182 ยท ASP.NET Core

REST API Design with ASP.NET Core

Design clean REST APIs in ASP.NET Core - resource modeling, status codes, pagination, idempotency, versioning, ETags, OpenAPI documents and a pragmatic take on HATEOAS, with runnable C# examples.

Anyone can make an endpoint return JSON. Designing an API that other developers enjoy using, that survives years of change, and that stays correct when clients retry, run in parallel or send junk is a different skill. API design is mostly about decisions that are expensive to change later: names of resources, shape of responses, how errors look, how you page through large lists, how you introduce a breaking change without breaking everyone.

This lesson collects the practices that hold up in real projects, each demonstrated with a running minimal API: modeling resources and choosing status codes, pagination, idempotency for safe retries, versioning, conditional requests with ETags, and describing the API with OpenAPI. It builds on Minimal APIs, Routing and Model Binding, Validation and Problem Details and Middleware.

As in the earlier ASP.NET Core lessons, each example runs a Kestrel server on loopback and calls it with HttpClient. The using lines are normally implicit in a web project; our single-file runner needs them spelled out. Data lives in memory so you can see the whole design in one file; a real service would use a database (see Data Access in .NET).

Model resources, not actions

REST ("representational state transfer") describes an architecture style, and in everyday use it means: URLs name things (resources), HTTP verbs say what to do with them, and status codes say what happened. Compare two designs for the same feature:

TEXT
RPC style (verbs in the URL)         Resource style
POST /createProduct                  POST   /products
GET  /getProduct?id=5                GET    /products/5
POST /updateProduct                  PUT    /products/5
POST /deleteProduct                  DELETE /products/5

The resource style is predictable. A developer who has seen /products can guess /customers, and standard tools (caches, proxies, API gateways, client generators) understand the verbs. Conventions that pay off:

  • Plural nouns for collections: /products, with items at /products/{id}.
  • Nesting for ownership, kept shallow: /customers/7/orders is fine; four levels deep is not. Once an order has its own id, /orders/123 is enough.
  • Verbs for what the verb means. GET reads and must not change anything (it is safe); PUT replaces and DELETE removes, and both are idempotent (repeating them leaves the same state); POST creates or triggers work and is not idempotent; PATCH changes part of a resource.
  • Actions that do not fit CRUD become sub-resources or commands: POST /orders/123/cancellation, POST /reports/generate. Pragmatism beats purity.
  • Lowercase, hyphenated URLs and one JSON naming style (ASP.NET Core defaults to camelCase).
  • Never expose database entities directly. Return dedicated response records so renaming a column does not break clients.

Status codes tell the story

Situation Status
Read or update succeeded, body returned 200 OK
Resource created 201 Created plus a Location header
Success with nothing to return (update, delete) 204 No Content
Malformed or invalid input 400 Bad Request (or 422)
Not signed in / not allowed 401 / 403
No such resource 404 Not Found
Conflicts with current state (duplicate, stale version) 409 Conflict / 412 Precondition Failed
Too many requests 429 with Retry-After
Server bug 500 (never intentionally)
C# A resource-style products 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.

Notice how the status codes narrate every step: 201 with a Location the client can follow, 204 for an update that returns nothing, and the second DELETE returning 404. (Whether a repeated DELETE should return 204 or 404 is a design choice; the state after it is identical either way, which is what idempotent means.)

Use separate types for input (NewProduct) and output (Product). The input type has no Id, so clients cannot choose it, which also prevents mass-assignment mistakes. See records for why immutable records are a natural fit.

Pagination: never return unbounded lists

GET /products is harmless with 20 rows and an outage with 20 million. Every collection endpoint needs a limit. Two main strategies:

  • Offset pagination (?page=3&pageSize=20, or ?offset=40&limit=20) is simple and allows jumping to any page. Its weaknesses: the database must skip all earlier rows (slow for deep pages), and if rows are inserted or deleted while a client pages, items are skipped or repeated.
  • Keyset (cursor) pagination (?after=<last id seen>&limit=20) asks for "the next 20 after this one". It is fast at any depth (the query uses an index seek) and stable under changes, but you cannot jump to page 50. Feeds, logs and infinite scroll should use it. Opaque cursors (a Base64 string) keep clients from relying on the internals.

Always cap the page size on the server, and tell the client how to continue, either in the body or with a Link header.

C# Offset and keyset pagination

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 offset endpoint reports totals so a UI can draw page buttons; the third request shows the server clamping an absurd pageSize. The keyset loop never asks for a page number: each answer carries the cursor for the next one, and nextCursor is null on the last page. Fetching size + 1 rows is a cheap trick to learn whether more data exists without a separate COUNT(*).

Idempotency: making retries safe

Networks fail. A client sends POST /payments, the connection drops, and it cannot tell whether the payment was created. Retrying might charge the customer twice. GET, PUT and DELETE are naturally idempotent, but POST is not, so APIs that move money or create important records support an idempotency key: the client generates a unique value (a GUID) per logical operation and sends it in an Idempotency-Key header. The server remembers the result for that key and replays it instead of repeating the work.

The tricky part is concurrency: two identical requests can arrive at the same moment. The trick below registers a Lazy<Task<T>> atomically per key, so the work starts once and every duplicate awaits the same result.

C# Idempotency-Key with concurrent duplicates

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.

Three requests with the same key produced one charge; the other two are marked as replays; a new key produced a second charge; and a request with no key was rejected. In a real service the dictionary would be a database table or Redis entry with an expiry (24 hours is common), and you should also store a hash of the request body so that reusing a key with different data returns 409 or 422.

Versioning: evolving without breaking clients

Once clients depend on your response shape, some changes are breaking: removing or renaming a field, changing a type, making an optional input required, changing the meaning of a value. Adding an optional field or a new endpoint is non-breaking, provided well-behaved clients ignore unknown fields. The best versioning strategy is to avoid needing it by only making additive changes. When you cannot, expose a new version side by side:

Strategy Example Notes
URL segment /v1/users, /v2/users Most visible and easiest to cache, test and route. The common choice.
Query string /users?api-version=2 Simple, but easy to forget.
Header Api-Version: 2 Clean URLs, harder to try in a browser.
Media type Accept: application/vnd.shop.v2+json "Purist", rarely worth the complexity.

The NuGet package Asp.Versioning.Http implements all of these, including version discovery and deprecation reporting. Without packages, route groups give you URL versioning for free, and a group-level filter can announce that the old version is on its way out using the Deprecation and Sunset response headers:

C# URL versioning with route groups

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.

Version at the API level (a whole surface at once), keep the number of live versions small, share logic below the endpoints so you are not maintaining two applications, announce deprecations early, and measure who still calls the old version before you switch it off.

Conditional requests: ETags and optimistic concurrency

HTTP has built-in answers to two problems. First, caching: why resend a large response if nothing changed? Second, lost updates: two users load the same record, both edit, and the second save silently overwrites the first. The mechanism is the ETag, an opaque version identifier of the representation:

  • The server sends ETag: "3" with a GET. The client later sends If-None-Match: "3". If it still matches, the server answers 304 Not Modified with no body.
  • For updates, the client sends If-Match: "3" with the PUT. If the resource has moved on, the server answers 412 Precondition Failed instead of overwriting.
C# ETag, If-None-Match and If-Match

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.

Ann's save succeeds and bumps the version. Ben's save, based on the old ETag, is refused with 412 instead of erasing Ann's work, and Ben's app can reload and merge. The same idea in a database is called optimistic concurrency (a row-version column that EF Core checks, see Entity Framework Core).

Describing your API: OpenAPI

An OpenAPI document is a machine-readable description (paths, parameters, schemas, responses) of your API. Tools generate documentation sites, client libraries in many languages, mock servers and contract tests from it, so publishing one is one of the highest-value things you can do for API consumers. Since .NET 9, ASP.NET Core ships document generation as the package Microsoft.AspNetCore.OpenApi, which is a NuGet package and so is not available in our single-file runner. Here is the setup in a project:

C#
// Read-only: needs the NuGet package Microsoft.AspNetCore.OpenApi
builder.Services.AddOpenApi();                 // register the generator

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();                          // serves /openapi/v1.json
}

app.MapGet("/api/products/{id:int}", (int id) => TypedResults.Ok(new Product(id, "Keyboard", 49.9m)))
   .WithName("GetProduct")
   .WithTags("Products")
   .WithSummary("Gets one product by id")
   .Produces<Product>(StatusCodes.Status200OK)
   .ProducesProblem(StatusCodes.Status404NotFound);

The generator reads endpoint metadata: names, tags, summaries, the types you declare with Produces, and the parameter types from your handler signature. Returning TypedResults (instead of Results) lets it infer response types automatically. You can see that metadata yourself, because it is just data attached to each endpoint. The program below walks the endpoint list and prints a tiny API description, which is conceptually what the OpenAPI generator does before it writes JSON:

C# Reading endpoint metadata like an OpenAPI generator

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 handler returns TypedResults, which already adds response metadata of its own; that is why the explicit Produces entries repeat a status and the code removes duplicates. The /health endpoint is hidden with ExcludeFromDescription(), exactly as you would keep internal endpoints out of the published document. Good OpenAPI hygiene: give every endpoint a stable WithName (it becomes the operationId that client generators turn into method names), declare every status code it can return, and tag endpoints so documentation is grouped sensibly.

HATEOAS: ideal and pragmatic

HATEOAS (hypermedia as the engine of application state) is the part of REST where responses include links that tell the client what it can do next, so the client follows links instead of building URLs:

JSON
{
  "id": 17,
  "status": "pending",
  "total": 59.80,
  "_links": {
    "self":   { "href": "/orders/17" },
    "cancel": { "href": "/orders/17/cancellation", "method": "POST" },
    "pay":    { "href": "/orders/17/payment", "method": "POST" }
  }
}

It is elegant: the server can change URLs and add or remove actions according to state (a shipped order simply lacks cancel), and clients react to the links they receive. In practice, most public APIs are not fully hypermedia-driven. Clients are written against documentation and generated from OpenAPI, so full HATEOAS adds payload size and tooling cost with modest benefit.

The pragmatic middle that many teams adopt: always return a Location header after creation; include next/prev links for pagination; and add action links only where the available actions depend on state and would otherwise force the client to duplicate business rules. Do not let the debate delay shipping a consistent, documented API.

A checklist before you ship

  • Resources are plural nouns; verbs match semantics; status codes are specific.
  • Every list endpoint is paginated with a server-side maximum.
  • Errors use one format (Problem Details); validation errors list every field.
  • Unsafe operations that clients may retry support idempotency keys; updates use ETags or version fields.
  • Input and output types are separate DTOs; no internal ids, columns or stack traces leak.
  • Authentication and authorization are applied by default (Authentication and Authorization).
  • Changes are additive; breaking changes get a new version with a deprecation window.
  • An OpenAPI document is published, and endpoints have names, tags and declared responses.
  • Rate limits, timeouts and request-size limits protect the service; all of them are tested.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status code and header should a successful POST /products that creates a product return?

    201 Created signals that a new resource exists, and the Location header tells the client where to find it.
  2. 2. Why is keyset (cursor) pagination often better than offset pagination for large, changing data?

    Keyset pagination seeks directly to the position after the last item seen, so deep pages stay fast and concurrent changes do not shift the pages. The cost is that you cannot jump to an arbitrary page.
  3. 3. A client sends the same POST /payments twice with the same Idempotency-Key. What should the server do?

    The key identifies one logical operation. The server stores the result for the key and returns it again for retries instead of repeating the side effect.
  4. 4. A PUT carries If-Match: "3" but the document is now at version 4. What is the correct response?

    If-Match makes the update conditional on the ETag. When it no longer matches, 412 protects the newer data from being silently overwritten.
  5. 5. Which of these is a non-breaking change to a JSON API response?

    Adding an optional field is additive; clients that ignore unknown fields keep working. Renaming, removing or retyping fields breaks existing clients and calls for a new version.

Summary

  • Name resources with plural nouns, let HTTP verbs carry the action, and return precise status codes (201 + Location, 204, 404, 409, 412).
  • Always paginate; use offset paging for small jumpable lists and keyset paging for large or fast-changing data, and cap page sizes on the server.
  • Support idempotency keys for retried POSTs, and use ETags with If-Match / If-None-Match for caching and lost-update protection.
  • Prefer additive changes; when you must break, version (URL segments are the simplest) and signal deprecation with headers.
  • Publish an OpenAPI document (Microsoft.AspNetCore.OpenApi) and enrich endpoints with names, tags and declared responses; the generator reads endpoint metadata.
  • Treat HATEOAS as a tool, not a religion: Location headers and pagination links cover most of its practical value.

Next: MVC, Razor Pages and Blazor