SiteTidy
HomeGuidesBuilding Scalable REST APIs (Part 1): Design the HTTP Contract First
Backend

Building Scalable REST APIs (Part 1): Design the HTTP Contract First

Design REST APIs around resources and HTTP semantics: URLs, methods, status codes, idempotency, validation, pagination and consistent errors.

Published on August 15, 2026Updated August 31, 2026
Building Scalable REST APIs (Part 1): Design the HTTP Contract First

A scalable API does not start with Kubernetes, queues or a larger database. It starts with a contract that still makes sense when the API has ten consumers instead of one.

That means getting the boring-looking decisions right: what a resource is, what each HTTP method means, how clients retry requests, how errors are represented, how collections are paginated and which behaviours clients can safely depend on.

If those decisions are inconsistent, infrastructure only lets you serve the inconsistency faster.

This first part builds the HTTP foundation. Later parts will deal with data access, caching, reliability, security and production operation.

REST is not a URL naming convention

Calling an endpoint /api/users does not make an API RESTful.

HTTP already gives us a useful application model: resources are identified by URIs, request methods carry semantics, representations describe resource state, response status codes communicate outcomes and headers carry metadata that intermediaries can understand.

A practical REST API works with those semantics rather than inventing a private protocol on top of POST.

For example, prefer:

GET    /customers/42
PATCH  /customers/42
DELETE /customers/42
GET    /customers/42/orders
POST   /customers/42/orders

over an RPC-shaped collection of endpoints such as:

POST /getCustomer
POST /updateCustomer
POST /deleteCustomer
POST /createCustomerOrder

RPC is not inherently bad. Sometimes an operation really is an operation. The problem is pretending everything is REST while discarding the semantics that make HTTP useful.

Model resources, not database tables

Your public API is a product boundary, not a remote SQL interface.

A customer resource might be assembled from several tables. A subscription may represent state owned by multiple services. Conversely, a table used only for implementation detail may deserve no public endpoint at all.

Design around concepts clients understand:

/customers/{customerId}
/subscriptions/{subscriptionId}
/invoices/{invoiceId}

Avoid leaking persistence choices into the contract:

/tblCustomerHeader/{id}
/customerSubscriptionJoin/{id}

This separation matters because databases change. Public contracts are much harder to change once mobile applications, partners and customer integrations depend on them.

Use HTTP methods according to their semantics

The method should tell a client something useful before it has read your documentation.

GET reads

GET retrieves a representation and is defined as a safe method. A GET request should not perform an action the client can reasonably be blamed for, such as cancelling an order or charging a card.

This is dangerous:

GET /orders/123/cancel

Crawlers, link checkers, browser prefetchers and caches all have reasons to treat GET as retrieval.

POST creates or processes

POST is deliberately flexible. It is commonly used to create a subordinate resource:

POST /orders
Content-Type: application/json

{
  "customerId": "cus_123",
  "items": [
    { "sku": "ABC-10", "quantity": 2 }
  ]
}

A successful creation will commonly return 201 Created and identify the new resource:

HTTP/1.1 201 Created
Location: /orders/ord_8472
Content-Type: application/json

POST is also reasonable for operations that do not map cleanly to CRUD, such as starting an export or submitting a payment attempt.

PUT replaces a known resource state

PUT is idempotent: repeating the same request is intended to have the same effect as sending it once.

A useful mental model is:

PUT this representation at this resource URI.

Do not casually describe PUT as “update” and PATCH as “partial update” without defining the replacement semantics your API actually implements.

PATCH applies a partial modification

PATCH is useful when the client needs to change only part of a resource:

PATCH /customers/42
Content-Type: application/merge-patch+json

{
  "displayName": "Northwind UK"
}

Define the patch media type and semantics rather than accepting an arbitrary JSON object whose behaviour clients have to reverse-engineer.

DELETE removes the resource association

DELETE is idempotent at the HTTP semantic level. That does not require every repeated request to return the same status code; it means repeating the request should not create additional intended effects.

Your contract should explicitly decide whether deleting an already absent resource returns 204, 404, or another domain-appropriate response.

Idempotency is a production feature, not theory

Networks fail in ambiguous ways.

A client sends a payment request. Your server commits it. The connection disappears before the response reaches the client.

Did the payment happen?

If the client blindly retries a non-idempotent POST, it may happen twice.

For operations where duplicate execution is expensive, support an idempotency key:

POST /payments
Idempotency-Key: 1f68f99d-7a32-4f61-a6ec-6c8857e16d71

The server associates that key with the operation and can return the original outcome when the same logical request is retried.

Important details are easy to miss:

  • scope keys appropriately, often by caller and operation;
  • expire them according to the retry window you promise;
  • reject reuse of a key with materially different request data;
  • make persistence of the key and the business operation atomic enough to avoid races;
  • document which endpoints support the mechanism.

Do not bolt this on after the first double charge.

Status codes are part of the contract

Clients should not need to parse English error messages to determine whether a request should be retried.

Useful distinctions include:

Status Typical meaning in an API
200 OK Request succeeded and a representation is returned
201 Created A resource was created
202 Accepted Work was accepted but has not completed
204 No Content Request succeeded with no response content
400 Bad Request Request is malformed or invalid at a general level
401 Unauthorized Authentication credentials are missing or unacceptable
403 Forbidden Caller is authenticated but not permitted to perform the operation
404 Not Found Target resource is not available to the caller
409 Conflict Request conflicts with current resource state
412 Precondition Failed A conditional request precondition failed
422 Unprocessable Content Content is understood but cannot be processed as supplied
429 Too Many Requests Caller has exceeded an applicable limit
500 Internal Server Error Unexpected server failure
503 Service Unavailable Service is temporarily unable to handle the request

There are nuances. Security-sensitive APIs may deliberately return 404 rather than revealing that a forbidden resource exists. Validation conventions vary. What matters is that the convention is intentional and stable.

Use a standard error shape

RFC 9457 defines Problem Details for HTTP APIs, replacing the older RFC 7807 specification. It gives clients a common machine-readable error structure using application/problem+json.

A validation response might look like:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
  "type": "https://api.example.com/problems/validation",
  "title": "The request is not valid",
  "status": 422,
  "detail": "One or more fields failed validation.",
  "instance": "/problems/01J6R6H3R1K6",
  "errors": [
    {
      "pointer": "/email",
      "code": "invalid_email",
      "message": "Enter a valid email address."
    }
  ]
}

The useful part is not the exact wording. It is that clients have stable fields and stable machine-readable identifiers.

Do not expose stack traces, SQL, internal hostnames or exception messages in public error details.

Separate validation from authorization

Suppose the client sends:

PATCH /accounts/123

with:

{
  "creditLimit": 500000
}

There are several different questions:

  1. Is the JSON syntactically valid?
  2. Is creditLimit a recognised field of the request contract?
  3. Is 500000 valid for the field?
  4. Is the transition valid for this account?
  5. Is this caller allowed to change this account?
  6. Is this caller allowed to change this property?

Those are not the same check.

This distinction becomes critical in API security. Binding arbitrary request JSON directly onto persistence/domain entities can create mass-assignment and property-level authorization problems.

Use explicit request DTOs and explicit authorization rules.

Collections need a contract too

This endpoint is easy to ship:

GET /orders

It is also a future outage if the response eventually contains 4.7 million orders.

Paginate collection endpoints from the beginning.

A simple page-number API can be appropriate for relatively stable administrative data:

GET /orders?page=3&pageSize=50

For large or rapidly changing datasets, cursor/keyset pagination is often more predictable:

GET /orders?limit=50&after=eyJpZCI6ODQ3Mn0

A response might expose navigation explicitly:

{
  "items": [ ... ],
  "page": {
    "nextCursor": "eyJpZCI6ODUyMn0",
    "hasMore": true
  }
}

Define ordering before cursor pagination

A cursor is only meaningful against a deterministic ordering.

For example:

ORDER BY created_at DESC, id DESC

The unique tie-breaker prevents rows with identical timestamps from moving unpredictably between pages.

Do not promise an expensive total count accidentally

totalCount looks convenient:

{
  "items": [],
  "totalCount": 187439284
}

On some datasets it is cheap. On others it becomes one of the most expensive queries in the system.

Only make exact totals part of the contract when clients genuinely need them and you know how you will produce them at scale.

Filtering and sorting need boundaries

Do not turn a REST endpoint into an unrestricted query language by accepting arbitrary property names and operators.

Prefer an explicit vocabulary:

GET /orders?status=open&customerId=42&sort=-createdAt

Then whitelist:

  • filterable fields;
  • sortable fields;
  • maximum page size;
  • allowed ranges;
  • search complexity.

This improves performance predictability and reduces injection and resource-consumption risks.

Avoid returning your database entities verbatim

Public representations should be deliberate.

If your ORM entity gains fields such as:

PasswordHash
InternalRiskScore
SupplierCost
DeletedAt

automatic serialization must not quietly turn them into public API fields.

Response DTOs also let the public contract evolve independently of internal storage.

public sealed record CustomerResponse(
    Guid Id,
    string DisplayName,
    string Email,
    DateTimeOffset CreatedAt);

This small amount of explicitness buys a lot of safety.

Design for concurrency, not just happy-path updates

Two users load the same customer. Both edit it. User A saves. User B saves thirty seconds later and silently overwrites A’s changes.

For resources where lost updates matter, use optimistic concurrency.

HTTP already has conditional requests. A server can return an ETag:

ETag: "customer-42-v17"

The client updates conditionally:

PATCH /customers/42
If-Match: "customer-42-v17"

If the representation has changed, the server can reject the stale mutation rather than overwriting newer data.

The same validator model becomes useful for caching, which we will cover later in the series.

Long-running work should not hold a request open forever

Generating a large report, transcoding a video or importing a million records may take minutes.

Instead of keeping an HTTP request alive until the work finishes, model the job as a resource:

POST /exports
HTTP/1.1 202 Accepted
Location: /exports/exp_123

The client can then inspect:

GET /exports/exp_123
{
  "id": "exp_123",
  "status": "running",
  "progress": 63
}

That design works naturally with queues and background workers without exposing the queue itself as the public contract.

Version only when you actually need a breaking contract

Versioning is useful, but it is not a substitute for compatibility discipline.

Adding an optional response property often does not require /v2. Renaming a field, changing its meaning, removing an enum member or making an optional input mandatory might.

Common strategies include URI versions:

/api/v1/orders

or media/header-based approaches. URI versions are obvious and operationally straightforward, which is why they remain common.

Whichever approach you choose, define:

  • what counts as a breaking change;
  • how long old versions are supported;
  • how deprecation is communicated;
  • how clients discover migration guidance;
  • how usage of old versions is measured before removal.

OpenAPI is useful, but the contract comes first

An OpenAPI document can generate clients, documentation, mocks and tests. It can also precisely document a badly designed API.

Treat the specification as an executable description of deliberate decisions rather than a file generated at the end because Swagger happens to be installed.

Good API reviews should be able to inspect the contract without reading controller code.

A practical first-pass contract review

Before worrying about horizontal scaling, take one important API and ask:

  • Are URLs resource-oriented and stable?
  • Do methods follow HTTP semantics?
  • Are unsafe operations accidentally exposed as GET?
  • Which POST operations need idempotency protection?
  • Are status codes meaningful and consistent?
  • Is there one machine-readable error model?
  • Are request and response DTOs explicit?
  • Are authorization and property-level authorization separate from validation?
  • Are collections bounded and deterministically ordered?
  • Are filters and sort fields whitelisted?
  • Do concurrent writes need ETags or another version check?
  • Are long-running operations represented asynchronously?
  • Is compatibility policy written down?

If those answers are solid, you have something worth scaling.

Check the web-facing layer too

API design happens behind the page, but production quality also depends on the HTTP, security and performance configuration users actually receive.

Run a SiteTidy Audit →

What comes next

A clean contract does not guarantee a scalable implementation. Part 2 moves behind the endpoint into the data path: query design, indexes, avoiding N+1 work, connection pools, pagination at scale, read models and the point where a cache helps rather than hides a database problem.

Ready to audit your site?

Put this guide into practice immediately using our free tools.

Browse 180+ Free Tools