Architecture PracticeComplete guide

API Design Best Practices

Good API design creates a clear, loosely coupled contract that clients can use correctly and evolve with safely.

Overview

An HTTP API should model consumer workflows and durable business resources rather than database tables or implementation methods. Consistent URIs, methods, status codes, representations, Problem Details, pagination, filtering, conditional requests, concurrency controls, idempotency, asynchronous operations, versioning, security, and observability make behavior predictable. Collection work must be bounded and retry behavior must be explicit: a cursor avoids unstable offsets, an idempotency key protects retried creation, and an ETag with If-Match prevents lost updates. Contract-first review and executable compatibility tests help providers and consumers evolve independently. Additive changes are usually safest, while removals and semantic changes need evidence of consumer usage, a published deprecation window, migration instructions, and a controlled version boundary. A good contract also specifies authorization, payload limits, rate-limit signals, cancellation, correlation, privacy, caching, and the difference between a transient failure that can be retried and a permanent client error.

What you will learn

  • Model APIs around consumer workflows and resource lifecycles.
  • Apply HTTP safety, idempotency, status, header, caching, and conditional-request semantics.
  • Design bounded cursor pagination and predictable validation errors.
  • Protect retried creation with idempotency keys and concurrent updates with ETags.
  • Evolve contracts through additive change, compatibility evidence, versioning, and deprecation.
  • Test the contract and operational behavior from a real client boundary.

Prerequisites

  • HTTP methods, status codes, headers, JSON, and REST resource vocabulary.
  • ASP.NET Core routing, dependency injection, Problem Details, and integration testing.
  • A .NET 10 SDK to run the dedicated orders sample.

When to use API Design Best Practices

Good fit

  • Use resource-oriented HTTP when consumers benefit from standard web semantics and broad tooling.
  • Use idempotency keys for retryable non-idempotent creation or commands.
  • Use ETags and If-Match when concurrent writers must not silently overwrite each other.

Choose another approach when

  • Do not expose tables or internal service methods as the public model.
  • Do not return unbounded collections or ambiguous generic errors.
  • Do not version every additive field or promise retry safety without a durable idempotency store.

Key concepts

Resource-oriented contracts

Stable nouns, representations, relationships, and workflow resources describe the domain without exposing internal storage or service boundaries.

HTTP semantics

Methods, safety, idempotency, status codes, headers, caching, conditional requests, and content negotiation communicate standard behavior.

Scale and resilience

Pagination, filtering, field selection, rate limits, timeouts, idempotency keys, and asynchronous operations bound work and support retries.

Evolution and governance

OpenAPI review, compatibility checks, explicit versioning, deprecation windows, security defaults, and telemetry protect clients over time.

Cursor pagination

An opaque continuation token gives clients a bounded traversal contract without coupling them to database offsets.

Idempotency records

A client key is stored with request identity and original outcome so safe retries replay but conflicting reuse is rejected.

Optimistic concurrency

ETag and If-Match let a server reject stale writes with 412 rather than silently losing another client's update.

Problem Details

A stable machine-readable error shape carries status, type, title, detail, field errors, and a safe correlation identifier.

Architecture

Clients use a versioned contract through security and policy controls; resource handlers enforce domain rules while telemetry and compatibility checks govern evolution.

Clients + SDKs
Contract + policy
Resource handlers
Domain + telemetry

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The dedicated orders sample turns contract rules into executable behavior: bounded cursor pagination, idempotent creation, Problem Details, ETags, If-Match preconditions, and integration tests for both successful and conflicting requests.

  1. 01
    Map consumer workflows

    Identify resources, actions, representations, permissions, latency expectations, and failure recovery from the caller's view.

  2. 02
    Choose HTTP semantics

    Assign methods, routes, status codes, headers, cache rules, and content types according to their standard meaning.

  3. 03
    Bound collections and payloads

    Set maximum page and body sizes and define opaque continuation tokens, filters, and ordering.

  4. 04
    Standardize failures

    Return Problem Details with stable types, validation members, safe details, and correlation IDs.

  5. 05
    Make retries safe

    Store idempotency key, request fingerprint, and original outcome in the same durable boundary as the effect.

  6. 06
    Protect concurrent writes

    Emit ETags and require If-Match for state replacement where lost updates matter.

  7. 07
    Govern evolution

    Publish OpenAPI, compatibility tests, version rules, usage telemetry, deprecation dates, and migration guidance.

Code example

A resource endpoint uses a constrained route, typed outcomes, cancellation, and a standard validation problem response.

Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

var app = builder.Build();
app.UseExceptionHandler();

app.MapPost("/orders", async (
    CreateOrder request, OrderService orders, CancellationToken ct) =>
{
    if (request.Lines.Count == 0)
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["lines"] = ["At least one order line is required."]
        });

    var order = await orders.CreateAsync(request, ct);
    return Results.Created($"/orders/{order.Id}", order);
});

app.Run();

Testing strategy

API tests should prove semantics that clients depend on, including retries and conflicts.

  • Use an in-memory HTTP host and send real serialized requests through routing and middleware.
  • Test collection bounds, cursor continuation, deterministic ordering, and invalid cursor handling.
  • Test same-key replay and different-payload idempotency-key conflict.
  • Test missing, current, and stale If-Match values and the resulting ETag change.
  • Assert Problem Details content type, status, validation members, and trace correlation.
  • Compare OpenAPI or consumer contracts for unintended breaking changes.

Security considerations

Every operation, resource identifier, property, and workload limit is a security boundary.

  • Authenticate the caller and authorize function, tenant, object, and writable properties server-side.
  • Validate allow-listed request DTOs and minimize response fields.
  • Bound body, collection, filter, concurrency, and downstream work; add abuse controls by identity and operation.
  • Never place secrets or sensitive personal data in URLs, logs, idempotency records, or Problem Details.
  • Use HTTPS and verify proxy, CORS, CSRF, and caching behavior for the actual client type.

Performance and scalability

Predictable contracts bound server work and let clients avoid wasteful transfers and retries.

  • Enforce maximum page size and use indexes matching cursor ordering and filters.
  • Use conditional GET or writes where concurrency and bandwidth justify them.
  • Avoid offset pagination for large changing collections when stable cursor traversal is required.
  • Set cancellation, deadlines, connection limits, and downstream timeouts.
  • Measure latency and errors by normalized operation, status, and consumer without high-cardinality URLs.

Deployment and operations

API compatibility includes the gateway, proxy, persistence, observability, and rollout sequence.

  • Run contract and integration tests against the release artifact.
  • Use a durable shared idempotency store in multi-instance production and define retention.
  • Verify proxy forwarding, HTTPS origin, payload limits, rate-limit headers, and cache behavior.
  • Deploy additive storage and server changes before clients depend on them.
  • Monitor old-version usage and complete deprecation only after communicated exit criteria.

Common problems and fixes

Clients receive duplicate resources after retry.

Likely cause: Creation has no durable idempotency record or instances do not share it.

Fix: Persist key, request fingerprint, and outcome atomically with the effect and share the store.

A retry returns 409 for the same key.

Likely cause: The client reused a key with a different request payload.

Fix: Generate one key per logical operation and replay exactly the original request.

Updates return 412 Precondition Failed.

Likely cause: The If-Match value is stale because the resource changed.

Fix: Fetch the latest representation, reconcile, and retry with its ETag.

Large collection requests time out.

Likely cause: Page size or filtering is unbounded or the cursor order lacks a supporting index.

Fix: Cap pages, validate filters, use stable indexed cursor columns, and measure the query plan.

Clients cannot interpret errors consistently.

Likely cause: Endpoints return unrelated strings, HTML, or undocumented shapes.

Fix: Adopt Problem Details with stable types and test each status.

An additive deployment breaks a generated client.

Likely cause: A supposedly additive schema change altered requiredness, operation identity, or strict parsing.

Fix: Run compatibility checks and consumer tests, then version genuinely breaking semantics.

Best practices

  • Design from consumer workflows and domain resources, publish an OpenAPI contract, and review it before implementation.
  • Apply standard HTTP semantics consistently and document every status, header, cache, and retry behavior.
  • Return Problem Details for machine-readable errors with safe correlation data.
  • Bound collections and work with cursor pagination, filters, payload limits, quotas, timeouts, and cancellation.
  • Persist idempotency records atomically with business effects and reject conflicting key reuse.
  • Use ETags and If-Match to prevent lost updates where concurrent writes matter.
  • Prefer additive evolution and define explicit version and deprecation policy for breaking changes.
  • Observe normalized operations, latency, status, abuse, and consumer adoption without logging sensitive payloads.

Production checklist

  • Routes and representations model consumer workflows rather than storage internals.
  • Methods, status codes, Location, caching, retry, and asynchronous semantics are documented.
  • Collections, payloads, filters, execution time, and concurrency are bounded.
  • Problem Details types and validation members are stable and safe.
  • Idempotency storage is durable, shared, atomic with effects, and has retention policy.
  • ETag and precondition rules are tested wherever lost updates matter.
  • Authentication, function, tenant, object, and property authorization are verified negatively.
  • OpenAPI compatibility, versioning, deprecation, telemetry, and rollback have owners.

Common interview questions

What makes an HTTP operation idempotent?

Repeating the same request has the same intended effect on server state as making it once. GET, PUT, DELETE, HEAD, and safe retry mechanisms should respect that property even if response codes differ.

When should an API return 202 Accepted?

When work has been accepted but will complete asynchronously. The response should identify a status resource or operation URL and document polling, completion, failure, and cancellation behavior.

How can an API evolve without breaking clients?

Prefer additive changes, tolerant readers, contract compatibility tests, explicit policies for breaking versions, usage telemetry, and a communicated deprecation window.

How do idempotency keys make POST retries safe?

The server durably associates a client key with the request fingerprint and original result, replaying an exact retry and rejecting reuse for different input.

What do ETag and If-Match prevent?

They implement optimistic concurrency: a write succeeds only against the version the client read, so a stale client cannot silently overwrite a newer update.

Why prefer cursor over offset pagination?

A cursor can provide stable bounded continuation over changing, indexed data without the increasing scan cost and duplicate or skipped rows common with offsets.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

API Design Orders

A .NET 10 API demonstrating bounded cursor pagination, idempotent creation, Problem Details, ETags, If-Match optimistic concurrency, and executable HTTP contract tests.

ASP.NET Core 10HTTP SemanticsProblem DetailsxUnit
dedicated-samplecursor-paginationidempotencyetagintegration-testing
Run
dotnet run --project src/ApiDesignOrders
Test
dotnet test ApiDesignOrders.slnx