REST APIs
suggest changeA REST API exposes your data as resources with URLs (/api/todos, /api/todos/42) and uses standard HTTP methods to act on them. Clients and servers exchange JSON, and the status code tells the client what happened.
| Method | Typical URL | Meaning | Success status |
|---|---|---|---|
GET |
/api/todos |
list resources | 200 OK |
GET |
/api/todos/42 |
read one resource | 200 OK (404 if missing) |
POST |
/api/todos |
create a resource | 201 Created + Location header |
PUT |
/api/todos/42 |
replace a resource | 200 OK or 204 No Content |
PATCH |
/api/todos/42 |
change some fields | 200 OK or 204 No Content |
DELETE |
/api/todos/42 |
delete a resource | 204 No Content |
GET, PUT and DELETE are idempotent: sending the same request twice leaves the server in the same state as sending it once, so clients can safely retry them. POST is not: a retried POST can create a duplicate.
In .NET you write REST servers with ASP.NET Core minimal APIs (or MVC controllers) and call REST services with HttpClient plus the System.Net.Http.Json extension methods.
The examples are .NET 10 file-based apps. Save the code as app.cs and run dotnet run app.cs. Each program starts a small API server on a free port (127.0.0.1:0), then calls it with HttpClient, so you see both sides at once. #:property PublishAot=false is needed because file-based web apps default to Native AOT, where reflection-based JSON serialization is disabled. A normal project doesn't need it.
A CRUD API with minimal APIs
This is a complete in-memory "todos" API with all five operations:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0"); // port 0 = pick any free port
var todos = new ConcurrentDictionary<int, Todo>();
int nextId = 0;
var api = app.MapGroup("/api/todos");
api.MapGet("/", () => TypedResults.Ok(todos.Values.OrderBy(t => t.Id)));
api.MapGet("/{id:int}", Results<Ok<Todo>, NotFound> (int id) =>
todos.TryGetValue(id, out var todo) ? TypedResults.Ok(todo) : TypedResults.NotFound());
api.MapPost("/", (NewTodo input) =>
{
var todo = new Todo(Interlocked.Increment(ref nextId), input.Title, false);
todos[todo.Id] = todo;
return TypedResults.Created($"/api/todos/{todo.Id}", todo);
});
api.MapPut("/{id:int}", Results<Ok<Todo>, NotFound> (int id, Todo input) =>
{
if (!todos.ContainsKey(id)) return TypedResults.NotFound();
var todo = input with { Id = id }; // the URL decides the id, not the body
todos[id] = todo;
return TypedResults.Ok(todo);
});
api.MapDelete("/{id:int}", Results<NoContent, NotFound> (int id) =>
todos.TryRemove(id, out _) ? TypedResults.NoContent() : TypedResults.NotFound());
await app.StartAsync();
string baseUrl = app.Urls.First();
// Call the API with plain HttpClient and print what goes over the wire
using var http = new HttpClient { BaseAddress = new Uri(baseUrl) };
async Task Show(HttpMethod method, string url, string? json = null)
{
using var req = new HttpRequestMessage(method, url);
if (json != null)
req.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var resp = await http.SendAsync(req);
string body = await resp.Content.ReadAsStringAsync();
string location = resp.Headers.Location is { } loc ? $" Location: {loc}" : "";
Console.WriteLine($"{method} {url} -> {(int)resp.StatusCode} {resp.StatusCode}{location}");
if (body.Length > 0) Console.WriteLine($" {body}");
}
await Show(HttpMethod.Post, "/api/todos", """{"title":"Buy milk"}""");
await Show(HttpMethod.Post, "/api/todos", """{"title":"Write article"}""");
await Show(HttpMethod.Get, "/api/todos");
await Show(HttpMethod.Put, "/api/todos/1", """{"id":99,"title":"Buy milk","done":true}""");
await Show(HttpMethod.Get, "/api/todos/1");
await Show(HttpMethod.Delete, "/api/todos/2");
await Show(HttpMethod.Get, "/api/todos/2");
await Show(HttpMethod.Get, "/api/todos/abc");
await app.StopAsync();
record NewTodo(string Title);
record Todo(int Id, string Title, bool Done);
Output:
POST /api/todos -> 201 Created Location: /api/todos/1
{"id":1,"title":"Buy milk","done":false}
POST /api/todos -> 201 Created Location: /api/todos/2
{"id":2,"title":"Write article","done":false}
GET /api/todos -> 200 OK
[{"id":1,"title":"Buy milk","done":false},{"id":2,"title":"Write article","done":false}]
PUT /api/todos/1 -> 200 OK
{"id":1,"title":"Buy milk","done":true}
GET /api/todos/1 -> 200 OK
{"id":1,"title":"Buy milk","done":true}
DELETE /api/todos/2 -> 204 NoContent
GET /api/todos/2 -> 404 NotFound
GET /api/todos/abc -> 404 NotFound
Things to notice:
MapGroupputs the shared/api/todosprefix in one place. You can also attach authorization, tags or filters to the whole group.- Route constraints like
{id:int}decide whether a route matches./api/todos/abcdoesn't match, so it returns404and never reaches your code. - Parameter binding is automatic. Route values (
int id) come from the URL. A complex type (NewTodo input) is read from the JSON body. TypedResultswith aResults<Ok<Todo>, NotFound>return type lists every possible response in the signature. That gives compile-time checking and lets OpenAPI document the endpoint (see below). You can also returnResults.Ok(...)as plainIResult, but then the response types aren't known.201 Createdcarries aLocationheader that points to the new resource. Clients use it instead of building the URL themselves.- JSON uses camelCase. ASP.NET Core serializes the
Todorecord as{"id":1,"title":...}, which is what JavaScript clients expect. - The URL is the source of truth. The
PUTbody said"id":99, but the handler uses the id from the route. Never let the body change which resource gets updated.
ConcurrentDictionary and Interlocked.Increment matter here: ASP.NET Core handles requests on many threads at once, so shared state must be thread-safe (see race conditions). A real API would use a database (see accessing databases) instead.
Errors, validation and problem details
A good API returns errors in a predictable, machine-readable format. The standard is problem details (RFC 9457): a JSON object with type, title, status and detail, sent as application/problem+json. ASP.NET Core can produce it for every error, and since .NET 10 it can also validate request bodies with data annotations:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddProblemDetails(); // errors become application/problem+json
builder.Services.AddValidation(); // .NET 10: validates [Required], [Range], ...
var app = builder.Build();
app.UseExceptionHandler(); // unhandled exceptions -> 500 problem details
app.UseStatusCodePages(); // empty 4xx/5xx responses -> problem details
app.Urls.Add("http://127.0.0.1:0");
var products = new Dictionary<int, Product> { [1] = new(1, "Keyboard", 49.99m) };
app.MapGet("/api/products/{id:int}", Results<Ok<Product>, NotFound> (int id) =>
products.TryGetValue(id, out var p) ? TypedResults.Ok(p) : TypedResults.NotFound());
app.MapPost("/api/products", Results<Created<Product>, ProblemHttpResult> (NewProduct input) =>
{
if (products.Values.Any(p => p.Name == input.Name))
return TypedResults.Problem(
title: "Duplicate product",
detail: $"A product named '{input.Name}' already exists.",
statusCode: StatusCodes.Status409Conflict);
var product = new Product(products.Count + 1, input.Name, input.Price);
products[product.Id] = product;
return TypedResults.Created($"/api/products/{product.Id}", product);
});
app.MapGet("/api/crash", string () => throw new InvalidOperationException("database is down"));
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
async Task Send(HttpMethod method, string url, string? json = null)
{
using var req = new HttpRequestMessage(method, url);
if (json != null) req.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var resp = await http.SendAsync(req);
Console.WriteLine($"{method} {url} -> {(int)resp.StatusCode} ({resp.Content.Headers.ContentType})");
Console.WriteLine($" {await resp.Content.ReadAsStringAsync()}");
}
await Send(HttpMethod.Post, "/api/products", """{"name":"","price":-5}""");
await Send(HttpMethod.Post, "/api/products", """{"name":"Keyboard","price":10}""");
await Send(HttpMethod.Post, "/api/products", """{"name":"Mouse","price":"cheap"}""");
await Send(HttpMethod.Get, "/api/products/42");
await Send(HttpMethod.Get, "/api/crash");
await app.StopAsync();
public record NewProduct([Required, StringLength(50)] string Name, [Range(0.01, 10_000)] decimal Price);
public record Product(int Id, string Name, decimal Price);
Output:
POST /api/products -> 400 (application/problem+json)
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"Name":["The Name field is required."],"Price":["The field Price must be between 0.01 and 10000."]},"traceId":"0HNPCHORFSEAT:00000001"}
POST /api/products -> 409 (application/problem+json)
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.10","title":"Duplicate product","status":409,"detail":"A product named 'Keyboard' already exists.","traceId":"0HNPCHORFSEAT:00000002"}
POST /api/products -> 400 (application/problem+json)
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","status":400,"traceId":"0HNPCHORFSEAT:00000003"}
GET /api/products/42 -> 404 (application/problem+json)
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.5","title":"Not Found","status":404,"traceId":"0HNPCHORFSEAT:00000004"}
GET /api/crash -> 500 (application/problem+json)
{"type":"https://tools.ietf.org/html/rfc9110#section-15.6.1","title":"An error occurred while processing your request.","status":500,"traceId":"0HNPCHORFSEAT:00000005"}
What each piece does:
AddValidation()checks[Required],[StringLength],[Range]and otherSystem.ComponentModel.DataAnnotationsattributes before your handler runs. Invalid input gets a400with anerrorsdictionary, one entry per field. The rules are found by a source generator, and it only looks at public types: ifNewProductis notpublic, validation silently does nothing.TypedResults.Problemreturns a problem details response with your own title and status, here409 Conflictfor a business rule. UseTypedResults.ValidationProblem(errors)for your own field errors.- Malformed JSON (
"price":"cheap") can't be bound, so the framework rejects it with400before validation even runs. UseStatusCodePages()turns empty error responses, like the404fromTypedResults.NotFound(), into problem details.UseExceptionHandler()catches unhandled exceptions and returns a generic500. The exception message ("database is down") is not sent to the client. That's what you want: internal error details can leak secrets. The error is logged on the server instead.traceIdis added automatically. When a user reports an error, this id finds the matching log entry.
Pick status codes carefully. The ones REST clients rely on:
| Status | Use it when |
|---|---|
400 Bad Request |
the request is malformed or fails validation |
401 Unauthorized |
no or invalid credentials |
403 Forbidden |
authenticated, but not allowed |
404 Not Found |
the resource doesn't exist |
409 Conflict |
the request conflicts with current state (duplicate, wrong state) |
412 Precondition Failed |
an If-Match ETag no longer matches (see below) |
422 Unprocessable Content |
some APIs use it instead of 400 for validation errors |
429 Too Many Requests |
rate limit hit; send Retry-After |
500 Internal Server Error |
a bug or failure on the server |
503 Service Unavailable |
temporarily down; clients may retry |
Calling a REST API: a typed client
On the client side, System.Net.Http.Json adds extension methods that combine an HTTP call with JSON (de)serialization: GetFromJsonAsync, PostAsJsonAsync, PutAsJsonAsync, PatchAsJsonAsync, DeleteFromJsonAsync and ReadFromJsonAsync. They use web defaults (camelCase, case-insensitive property names).
Don't scatter URLs and JSON handling across your code. Wrap the API in a typed client: a class that takes an HttpClient and exposes ordinary C# methods. The program below also shows paging and filtering with query parameters, and enums sent as strings:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.HttpResults;
// ---- server ----
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddProblemDetails();
builder.Services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.Converters.Add(new JsonStringEnumConverter())); // "High" instead of 2
var app = builder.Build();
app.UseStatusCodePages();
app.Urls.Add("http://127.0.0.1:0");
var tasks = new List<TaskItem>();
for (int i = 1; i <= 7; i++)
tasks.Add(new TaskItem(i, $"Task {i}", (Priority)(i % 3)));
app.MapGet("/api/tasks", ([AsParameters] TaskQuery q) =>
{
IEnumerable<TaskItem> items = tasks;
if (q.Priority is { } p) items = items.Where(t => t.Priority == p);
var list = items.ToList();
var page = list.Skip((q.Page - 1) * q.PageSize).Take(q.PageSize).ToList();
return TypedResults.Ok(new PagedResult<TaskItem>(page, q.Page, q.PageSize, list.Count));
});
app.MapGet("/api/tasks/{id:int}", Results<Ok<TaskItem>, NotFound> (int id) =>
tasks.FirstOrDefault(t => t.Id == id) is { } t ? TypedResults.Ok(t) : TypedResults.NotFound());
app.MapPost("/api/tasks", Results<Created<TaskItem>, ValidationProblem> (NewTask input) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
return TypedResults.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title must not be empty."],
});
var task = new TaskItem(tasks.Max(t => t.Id) + 1, input.Title, input.Priority);
tasks.Add(task);
return TypedResults.Created($"/api/tasks/{task.Id}", task);
});
await app.StartAsync();
// ---- client ----
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
var client = new TasksClient(http);
var page = await client.ListAsync(page: 2, pageSize: 3);
Console.WriteLine($"page {page.Page}, {page.Items.Count} of {page.TotalCount} items:");
foreach (var t in page.Items) Console.WriteLine($" {t}");
var high = await client.ListAsync(priority: Priority.High);
Console.WriteLine($"high priority: {string.Join(", ", high.Items.Select(t => t.Title))}");
var created = await client.CreateAsync(new NewTask("Ship it", Priority.High));
Console.WriteLine($"created: {created}");
Console.WriteLine($"get 3: {await client.GetAsync(3)}");
Console.WriteLine($"get 99: {(await client.GetAsync(99))?.ToString() ?? "null"}");
try
{
await client.CreateAsync(new NewTask("", Priority.Low));
}
catch (ApiException ex)
{
Console.WriteLine($"{ex.StatusCode}: {ex.Message}");
foreach (var (field, errors) in ex.Errors)
Console.WriteLine($" {field}: {string.Join(" ", errors)}");
}
await app.StopAsync();
// A typed client: one place that knows URLs, JSON and error handling
public class TasksClient(HttpClient http)
{
static readonly System.Text.Json.JsonSerializerOptions Json = new(System.Text.Json.JsonSerializerDefaults.Web)
{
Converters = { new JsonStringEnumConverter() },
};
public async Task<PagedResult<TaskItem>> ListAsync(int page = 1, int pageSize = 10,
Priority? priority = null, CancellationToken ct = default)
{
var url = $"api/tasks?page={page}&pageSize={pageSize}";
if (priority != null) url += $"&priority={priority}";
return (await http.GetFromJsonAsync<PagedResult<TaskItem>>(url, Json, ct))!;
}
public async Task<TaskItem?> GetAsync(int id, CancellationToken ct = default)
{
using var resp = await http.GetAsync($"api/tasks/{id}", ct);
if (resp.StatusCode == HttpStatusCode.NotFound) return null;
await EnsureSuccess(resp, ct);
return await resp.Content.ReadFromJsonAsync<TaskItem>(Json, ct);
}
public async Task<TaskItem> CreateAsync(NewTask task, CancellationToken ct = default)
{
using var resp = await http.PostAsJsonAsync("api/tasks", task, Json, ct);
await EnsureSuccess(resp, ct);
return (await resp.Content.ReadFromJsonAsync<TaskItem>(Json, ct))!;
}
static async Task EnsureSuccess(HttpResponseMessage resp, CancellationToken ct)
{
if (resp.IsSuccessStatusCode) return;
Problem? problem = null;
if (resp.Content.Headers.ContentType?.MediaType == "application/problem+json")
problem = await resp.Content.ReadFromJsonAsync<Problem>(Json, ct);
throw new ApiException(resp.StatusCode, problem?.Title ?? resp.ReasonPhrase ?? "HTTP error",
problem?.Errors ?? new Dictionary<string, string[]>());
}
}
public class ApiException(HttpStatusCode status, string message, IDictionary<string, string[]> errors)
: Exception(message)
{
public HttpStatusCode StatusCode { get; } = status;
public IDictionary<string, string[]> Errors { get; } = errors;
}
// RFC 9457 problem details, as sent by ASP.NET Core
public record Problem(string? Type, string? Title, int? Status, string? Detail,
Dictionary<string, string[]>? Errors);
public enum Priority { Low, Normal, High }
public record TaskItem(int Id, string Title, Priority Priority);
public record NewTask(string Title, Priority Priority);
public record TaskQuery(int Page = 1, int PageSize = 10, Priority? Priority = null);
public record PagedResult<T>(List<T> Items, int Page, int PageSize, int TotalCount);
Output:
page 2, 3 of 7 items:
TaskItem { Id = 4, Title = Task 4, Priority = Normal }
TaskItem { Id = 5, Title = Task 5, Priority = High }
TaskItem { Id = 6, Title = Task 6, Priority = Low }
high priority: Task 2, Task 5
created: TaskItem { Id = 8, Title = Ship it, Priority = High }
get 3: TaskItem { Id = 3, Title = Task 3, Priority = Low }
get 99: null
BadRequest: One or more validation errors occurred.
title: Title must not be empty.
Things to notice:
[AsParameters]binds the properties ofTaskQueryfrom the query string (?page=2&pageSize=3&priority=High). Default values in the record make every parameter optional.- Return a page object, not a bare array.
PagedResult<T>includesTotalCount, so clients know how many pages exist. A JSON object can also gain fields later without breaking clients, while a top-level array can't. - Enums as strings.
JsonStringEnumConvertersends"High"instead of2. Numbers break silently when someone reorders the enum. Server and client must agree, so the client adds the same converter. BaseAddressand relative URLs. The client uses"api/tasks"without a leading slash. With a base address likehttps://host/v2/, a leading slash would drop the/v2/part.404is not always an error.GetAsyncreturnsnullfor a missing task because "not found" is a normal answer to "get task 99". Other failures become anApiExceptionthat carries the status code and the problem details sent by the server.- Don't use
GetFromJsonAsyncwhen you need the error body. It throwsHttpRequestExceptionon any non-success status and discards the response. That's fine forListAsync, but when you want the details, callGetAsync/PostAsJsonAsyncand check the status yourself, asEnsureSuccessdoes. - The client defines its own
Problemrecord.ProblemDetailslives in ASP.NET Core assemblies, which a plain console or desktop client doesn't reference. - Pass
CancellationTokenthrough every method, so callers can cancel slow requests (see cancellation and timeouts).
For URL values that come from users, escape them with Uri.EscapeDataString before putting them in the query string (see parsing URLs).
IHttpClientFactory and retries
Creating a new HttpClient for every request exhausts sockets, while one static HttpClient that lives forever never notices DNS changes. In apps that use dependency injection, register typed clients with AddHttpClient<T>(). IHttpClientFactory pools and recycles the underlying handlers for you.
Networks fail, so production clients also need timeouts and retries. The Microsoft.Extensions.Http.Resilience package adds a standard pipeline (rate limiter, total timeout, retry with exponential backoff, circuit breaker, per-attempt timeout) with one call:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
#:package Microsoft.Extensions.Http.Resilience@10.10.0
using System.Net.Http.Json;
// A flaky server: the first two requests fail with 503
var server = WebApplication.CreateBuilder();
server.Logging.ClearProviders();
var api = server.Build();
api.Urls.Add("http://127.0.0.1:0");
int calls = 0;
api.MapGet("/api/quote", () =>
{
int n = Interlocked.Increment(ref calls);
Console.WriteLine($" server: request #{n}");
return n <= 2 ? Results.StatusCode(503) : Results.Ok(new Quote("MSFT", 512.34m));
});
await api.StartAsync();
// Client app: register a typed client with IHttpClientFactory
var builder = Host.CreateApplicationBuilder();
builder.Logging.ClearProviders();
builder.Services.AddHttpClient<QuotesClient>(c =>
{
c.BaseAddress = new Uri(api.Urls.First());
c.DefaultRequestHeaders.UserAgent.ParseAdd("quotes-app/1.0");
})
.AddStandardResilienceHandler(o =>
{
o.Retry.Delay = TimeSpan.FromMilliseconds(100); // keep the demo fast
o.Retry.MaxRetryAttempts = 3;
});
using var host = builder.Build();
var quotes = host.Services.GetRequiredService<QuotesClient>();
Console.WriteLine($"got {await quotes.GetAsync()}");
await api.StopAsync();
public class QuotesClient(HttpClient http)
{
public async Task<Quote> GetAsync(CancellationToken ct = default) =>
(await http.GetFromJsonAsync<Quote>("api/quote", ct))!;
}
public record Quote(string Symbol, decimal Price);
Output:
server: request #1
server: request #2
server: request #3
got Quote { Symbol = MSFT, Price = 512.34 }
The first two attempts got 503 Service Unavailable. The resilience handler retried them, and QuotesClient only saw the successful third response. By default it retries 408, 429, 5xx and network errors, and respects Retry-After. It retries POST too, so make create operations safe to repeat, for example with a client-generated id or an Idempotency-Key header that the server remembers. In ASP.NET Core apps the same AddHttpClient code goes into builder.Services, and you get QuotesClient injected into your endpoints or services.
Optimistic concurrency with ETags
Two users load the same resource, both edit it, both save: without protection, the second save silently overwrites the first. REST solves this with ETags. The server sends a version tag in the ETag header. The client sends it back in If-Match when it updates. If the resource has changed since, the server answers 412 Precondition Failed.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Net.Http.Headers;
using System.Net.Http.Json;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0");
var doc = new Doc(1, "Draft", Version: 1);
var gate = new object();
app.MapGet("/api/docs/1", (HttpResponse res) =>
{
res.Headers.ETag = $"\"{doc.Version}\"";
return TypedResults.Ok(doc);
});
app.MapPatch("/api/docs/1", (DocPatch patch, HttpRequest req, HttpResponse res) =>
{
lock (gate)
{
string current = $"\"{doc.Version}\"";
string? ifMatch = req.Headers.IfMatch;
if (ifMatch is null)
return Results.Problem("Send If-Match with the ETag you read.", statusCode: 428);
if (ifMatch != current)
return Results.Problem("The document was changed by someone else.", statusCode: 412);
doc = doc with { Title = patch.Title ?? doc.Title, Version = doc.Version + 1 };
res.Headers.ETag = $"\"{doc.Version}\"";
return Results.Ok(doc);
}
});
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
// Two clients read the same version
using var r1 = await http.GetAsync("/api/docs/1");
using var r2 = await http.GetAsync("/api/docs/1");
EntityTagHeaderValue etag1 = r1.Headers.ETag!, etag2 = r2.Headers.ETag!;
Console.WriteLine($"both read ETag {etag1}");
async Task Patch(string who, EntityTagHeaderValue? etag, string title)
{
using var req = new HttpRequestMessage(HttpMethod.Patch, "/api/docs/1")
{
Content = JsonContent.Create(new DocPatch(title)),
};
if (etag != null) req.Headers.IfMatch.Add(etag);
using var resp = await http.SendAsync(req);
Console.WriteLine($"{who}: {(int)resp.StatusCode} {await resp.Content.ReadAsStringAsync()}");
}
await Patch("client 1", etag1, "Final"); // wins
await Patch("client 2", etag2, "Other"); // stale ETag -> 412
await Patch("client 3", null, "Blind"); // no If-Match -> 428
await app.StopAsync();
record Doc(int Id, string Title, int Version);
record DocPatch(string? Title);
Output:
both read ETag "1"
client 1: 200 {"id":1,"title":"Final","version":2}
client 2: 412 {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.13","title":"Precondition Failed","status":412,"detail":"The document was changed by someone else.","traceId":"0HNPCHPAPG1TF:00000004"}
client 3: 428 {"title":"Precondition Required","status":428,"detail":"Send If-Match with the ETag you read.","traceId":"0HNPCHPAPG1TF:00000005"}
Client 2's update was rejected instead of overwriting client 1's change. Client 2 should now re-read the document, merge or ask the user, and try again. 428 Precondition Required forces clients to use ETags at all. ETag values must be quoted strings, which EntityTagHeaderValue handles on the client side. With a database, use a row version column (Entity Framework's [Timestamp] / concurrency tokens) as the ETag. The same header with If-None-Match on a GET lets clients skip downloading unchanged data (304 Not Modified). See HTTP headers for more about working with headers.
PATCH here takes a small DTO where null means "don't change". That works for simple cases. For APIs where null is a valid value, use JSON Merge Patch (application/merge-patch+json) or JSON Patch.
Documenting the API with OpenAPI
An OpenAPI document describes every endpoint, parameter and response in a format that tools understand: Swagger UI, Scalar, Postman, and client code generators such as Kiota or NSwag. ASP.NET Core generates it from your minimal API definitions:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
#:package Microsoft.AspNetCore.OpenApi@10.0.12
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddOpenApi();
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0");
app.MapOpenApi(); // serves /openapi/v1.json
var books = app.MapGroup("/api/books").WithTags("Books");
books.MapGet("/{id:int}", Results<Ok<Book>, NotFound> (int id) =>
id == 1 ? TypedResults.Ok(new Book(1, "Dune")) : TypedResults.NotFound())
.WithName("GetBook")
.WithSummary("Get a book by id");
books.MapPost("/", (Book b) => TypedResults.Created($"/api/books/{b.Id}", b))
.WithSummary("Add a book");
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
var spec = JsonNode.Parse(await http.GetStringAsync("/openapi/v1.json"))!;
foreach (var (path, ops) in spec["paths"]!.AsObject())
foreach (var (method, op) in ops!.AsObject())
{
var codes = string.Join(", ", op!["responses"]!.AsObject().Select(r => r.Key));
Console.WriteLine($"{method.ToUpper(),-5} {path,-18} {op["summary"],-18} responses: {codes}");
}
await app.StopAsync();
public record Book(int Id, string Title);
Output:
GET /api/books/{id} Get a book by id responses: 200, 404
POST /api/books Add a book responses: 201
The 200, 404 responses come straight from the Results<Ok<Book>, NotFound> return type: this is the main reason to prefer TypedResults over Results. For IResult handlers, describe responses with .Produces<T>(200) and .ProducesProblem(404). Open /openapi/v1.json in a browser to see the whole document. To get an interactive UI, add a package such as Scalar.AspNetCore and call app.MapScalarApiReference().
Designing a good REST API
- Use nouns for resources and HTTP methods for actions:
POST /api/orders, notPOST /api/createOrder. Use plural collection names and nest only for real ownership (/api/orders/42/items). - Return the right status code.
200with{"error": "..."}in the body breaks every generic client, retry policy and monitoring tool. - Separate DTOs from database entities. Request and response records like
NewTododecide exactly which fields clients can send and see. Binding straight to an entity lets clients set fields they shouldn't (over-posting), such asIsAdminorId. - Version the API before the first public release: a URL prefix (
/api/v1/...) is the simplest and the most visible. Adding optional fields is not a breaking change. Removing or renaming fields is. - Paginate every collection. Clamp
pageSizeto a maximum on the server so a single request can't fetch a million rows. - Secure it. Use HTTPS (see TLS and HTTPS), authenticate with tokens (
.RequireAuthorization()on a group), add rate limiting (AddRateLimiter/.RequireRateLimiting()), and configure CORS only if browsers on other origins must call the API. - Use
DateTimeOffsetand ISO 8601 for times in JSON, anddecimal(as a JSON number or string) for money. - Don't leak internals. Never return exception messages or stack traces from production endpoints. Problem details with a
traceIdgive users something to report without exposing details.