Volume 2 · Chapter 7 — ASP.NET Core Enterprise Development
Web API Design and REST Principles
7.1 Introduction
An enterprise API is a long-lived contract between systems, teams, and external partners, so it must be consistent, secure, discoverable, and evolvable. REST provides guidelines for designing APIs around resources and HTTP semantics rather than implementation details. Good API design is less about the technology and more about clear contracts, correct HTTP usage, versioning, idempotency, and consistency - the properties that make an API pleasant to consume and safe to change.
7.2 Resource-Oriented Design and HTTP Semantics
REST models the domain as resources addressed by URLs and manipulated with HTTP verbs and status codes. Resources are nouns (/customers/123/orders), not RPC-style verbs (/GetCustomerOrders); verbs express intent (GET reads, POST creates, PUT replaces, PATCH partially updates, DELETE removes); and status codes convey the outcome so clients can react programmatically.
| Status | Meaning |
|---|---|
| 200 / 201 / 204 | OK / Created / No Content |
| 400 / 401 / 403 | Bad request / Unauthenticated / Forbidden |
| 404 / 409 | Not found / Conflict |
| 429 / 500 | Too many requests / Server error |
7.3 DTOs: Contract Independence
APIs should expose Data Transfer Objects, not internal domain entities. DTOs give a stable contract, prevent accidental exposure of internal fields, let the internal model evolve independently, and let you trim payloads to what clients need.
// Map the domain entity to a DTO - never serialize the entity directly.
public sealed record CustomerDto(Guid Id, string Name, string Email);
app.MapGet("/customers/{id:guid}", async (Guid id, ICustomerService svc, CancellationToken ct) =>
{
var c = await svc.GetAsync(id, ct);
return c is null ? Results.NotFound()
: Results.Ok(new CustomerDto(c.Id, c.Name, c.Email)); // DTO, not entity
});
7.4 Versioning, Pagination, and Idempotency
APIs evolve, so versioning (URL, header, or query) lets you introduce breaking changes without breaking existing consumers - make additive changes backward-compatible and reserve new versions for breaking ones. Large collections must be paginated, filtered, and sorted rather than returned unbounded. And idempotency - via an idempotency key - ensures a retried request (from a network failure) produces the same result, which is critical in financial systems where a retry must not charge twice.
// GET /orders?page=1&pageSize=50&status=active&sort=date
// POST /payments with header Idempotency-Key: 9f3c... -> a retry returns the original result
7.5 Consistent Errors and OpenAPI
Enterprise APIs return a consistent, machine-readable error contract (ideally RFC 7807 problem details) with a stable code, safe message, and correlation id - never a stack trace. And they publish a machine-readable OpenAPI contract (Swagger) that drives documentation, client generation, and contract testing, turning the API into a discoverable, governed product.
// Consistent error contract:
// { "code": "PAYMENT_FAILED", "message": "Payment could not be processed", "correlationId": "12345" }
Why should an API expose DTOs instead of database entities?
Because the API’s wire format is a public contract that consumers depend on, and coupling it directly to your internal entities is dangerous on several fronts. Stability: if you serialize entities, any change to the entity - renaming a property, adding a field, changing the model for internal reasons - silently changes the API and can break consumers, whereas a DTO is a deliberate, stable contract you evolve independently of the internal model. Security: entities often contain fields consumers should never see - internal flags, audit columns, related data, sensitive information - and serializing them risks over-exposing data (and, on input, over-posting / mass-assignment attacks where a client sets fields it shouldn’t); a DTO exposes only the intended fields. Decoupling: with DTOs, the domain model and the API contract can evolve on their own timelines - you can refactor the internal model without touching the API, and version the API without contorting the domain. Shape and efficiency: a DTO can be tailored to exactly what a given endpoint or client needs, trimming payloads and flattening or aggregating data, rather than being dictated by the storage model. There’s also a practical EF concern: serializing tracked entities can trigger lazy loading, circular references, and leaking of navigation properties. So the DTO is a mapping boundary between your internal representation and your external contract, giving you a stable, secure, independently-evolvable, appropriately-shaped API. The small cost of writing and mapping DTOs is well worth it, which is why exposing DTOs (not entities) is a standard best practice for enterprise APIs.
Why is idempotency important for an API, and how do you implement it?
Idempotency means that making the same request multiple times has the same effect as making it once, and it matters because in distributed systems retries are inevitable - a client times out and resends, a user double-clicks, a network hiccup causes a retry, or a gateway retries - and without idempotency those duplicates cause real harm: a payment charged twice, an order created twice. It’s especially critical for financial and state-changing operations. GET, PUT, and DELETE are naturally idempotent by HTTP semantics, but POST (create) is not, so that’s where you add explicit idempotency. The standard implementation is an idempotency key: the client generates a unique key per logical operation and sends it (typically in anIdempotency-Keyheader); the server records processed keys along with their result, so when a request arrives, it checks whether that key has been seen - if not, it processes the operation and stores the key and outcome; if it has, it returns the original stored result without re-executing, guaranteeing exactly-once effect. The key store must be durable and handle concurrency (two simultaneous requests with the same key), and keys expire after a reasonable window. Alternatively, some operations can be made naturally idempotent (an upsert keyed by a business id, or a “set to X” rather than “add X”). Combined with this, the server returns consistent responses for retries. So idempotency is important because it makes retries safe - and retries are unavoidable - and you implement it with idempotency keys that dedupe requests and return the original result on repeats, which for a bank is the difference between a reliable payment API and one that double-charges customers.
How do you design an API for long-term compatibility as it evolves over years?
I treat the API as a published contract that consumers depend on and deploy against independently, so the guiding principle is: never break existing consumers. Concretely, I make changes additive and backward-compatible by default - adding new optional fields, new endpoints, new resources - which existing clients simply ignore, so they keep working; and I design consumers and responses to be tolerant (ignore unknown fields, don’t depend on field order). When a genuinely breaking change is unavoidable - removing or renaming a field, changing semantics - I version the API (via URL, header, or media type, chosen for the ecosystem), run the old and new versions in parallel during a clearly communicated deprecation window, and retire the old only after telemetry confirms consumers have migrated. I expose DTOs, never entities, so the internal model can evolve without forcing API changes, and I keep contracts consistent - standard error format (problem details), pagination, filtering, auth, and naming conventions - so the whole API is predictable and one part can be learned from another. I publish a machine-readable OpenAPI contract and use consumer-driven contract tests (Pact) so I know exactly who depends on what and can detect incompatibilities before shipping. I also design in the constructs that support evolution from the start - versioning strategy, idempotency, and clear deprecation policy - rather than retrofitting them. And I govern it: at enterprise scale, shared standards and templates ensure every API follows the same compatibility rules. The result is that producers and consumers can evolve on their own schedules without breaking each other, which is the entire purpose of versioning and stable contracts. In short: additive-by-default, tolerant readers, explicit versioning with parallel running for breaking changes, DTO boundaries, consistent contracts, OpenAPI plus contract testing, and clear deprecation - which together keep an API compatible and evolvable over its long life.
7.6 Enterprise API Scenario
A banking platform exposes transaction APIs consumed by mobile apps, internal services, and external partners. The design uses resource-oriented endpoints with correct HTTP semantics, DTO contracts (never exposing entities), header-based versioning, idempotency keys on payment operations, a standardized problem-details error contract with correlation ids, OAuth2 authentication, pagination on collections, and an OpenAPI contract driving docs and contract tests - a stable, secure, evolvable API surface serving many diverse consumers.
Chapter Revision Notes
- Model resources as nouns; use correct HTTP verbs and meaningful status codes.
- Expose DTOs, not entities - stable contracts, security, independent evolution.
- Version additively; paginate collections; use idempotency keys for state-changing operations.
- Return a consistent problem-details error contract with a correlation id.
- Publish OpenAPI to drive docs, client generation, and contract testing.